Why does the class accept parameter and the method does not?

Asked

Viewed 107 times

0

I’m studying classes in Python and I don’t understand one thing: considering the last two command lines below, why the value 4 is accepted in the class Operators and not in the method metade()? Do not these accept the parameters? If I put, the code does not execute.

class Operadores:
    def __init__(self, a):
        self.a = a
    
    def metade(self):
        return self.a/2
    
    def dobro(self):
        return self.a*2

    def triplo(self):
        return self.a*3

pass

operacao1 = Operadores(4)

print(operacao1.metade())

1 answer

7

There is no class that accepts parameter, class has no parameters. There is an object constructor of a class called init() which accepts to receive an argument because it is declared that this method has a parameter. When building the object you call by class name to indicate which init() must be called, but it is not the class that accepts argument, let alone parameter.

The method metade() has not declared any parameter to receive beyond the object itself through the self, then the code cannot accept arguments, if you want it to accept, then you must declare it. But the internal code doesn’t make much sense because nothing is being necessary.

The self is adopted to say that that parameter is the object itself, so the argument used will be written before the method, and so do the object-oriented syntax in which the main object is calling the function to be executed. At the bottom that’s an argument, but it doesn’t seem to be in the call syntax.

You only declare that there will be a parameter if it is necessary.

Useful: What is the difference between parameter and argument?.

Browser other questions tagged

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