How to declare and use methods that are in the same class

Asked

Viewed 85 times

1

Good afternoon. I would like to know how the declaration is made and the use of methods within the same class. For example, in one class there are 2 methods, which 1 method uses the other.

For example:

class ClasseEMetodo:
    def retorna_valor:
        return '10'

    def imprimi_valor:
        print('O valor é {0}' retorna_valor())


# chamada
var = ClasseEMetodo
var.imprimi_valor()

The error shown is:

    def retorna_valor:
                     ^
SyntaxError: invalid syntax
  • Basically https://answall.com/questions/176543/por-que-temos-que-utilizar-o-attributeself-como-argument-nos-m%C3%A9todos , and in your case you have some more mixed syntax errors: https://repl.it/repls/StarryIndianredOs

1 answer

1


class ClasseEMetodo:
    @classmethod
    def retorna_valor(cls):
        return '10'

    @classmethod
    def imprimi_valor(cls):
        print('O valor é {0}'.format(cls.retorna_valor()))


# chamada
var = ClasseEMetodo
var.imprimi_valor()  # O valor é 10
  • What is the (cls)?

  • cls -- ClasseEMetodo. print(cls) # <class '__main__.ClasseEMetodo'>, print(ClasseEMetodo) # <class '__main__.ClasseEMetodo'>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.