Function within a function

Asked

Viewed 61 times

1

I’m doing some tests and I’d like to understand why when my role somadez() is called is returned to me that function soma() was not defined being that the same when it is called works.

Follows the code:

class op():
    def __init__(self,num1,num2):
        self.x = num1
        self.y = num2

    def soma(self):
        return self.x+self.y

    def somadez(self):
        return soma()+10

conta1 = op(1,2)
print(conta1.soma())
print(conta1.somadez())

1 answer

2


You don’t have a function there, you have a method, at least by the convention adopted that if you have a self as parameter is a method, so methods can only be called through an object, cannot be called directly.

When called in conta1.soma() you called for a method, passing the object, but when you called for soma() + 10 did not use any object to pass the parameter self. As the only object you have within the method somadez() is the self that it received becomes easy to solve, just use it as object to call the desired method.

class op():
    def __init__(self, num1, num2):
        self.x = num1
        self.y = num2

    def soma(self):
        return self.x + self.y

    def somadez(self):
        return self.soma() + 10

conta1 = op(1, 2)
print(conta1.soma())
print(conta1.somadez())

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Note that Python has one syntax sugar which allows calling the method by passing the object to the self with the object rating before the method.

This has nothing to do with function within function. is about the scope of the self, it does not hold for every class, it needs to be passed explicitly.

  • Thank you! Clarified my doubts!

Browser other questions tagged

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