Skip to content Skip to sidebar Skip to footer

Python Calling A Function From Another Function In A Class

I am trying to learn python and am having difficulty in understanding why this class throws a error NameError: name 'self' is not defined .I have followed How to call a function wi

Solution 1:

You forgot to put the self in the method signature of main(). It should look like this

defmain(self):
        self.square(3)

Without that, self is in fact not defined in the scope of your method, so Python complains.

EDIT: also, as Some programmer dude mentions, your code never creates an instance of the class just executes main. There's also a problem with your indentation (probably a copy-paste error).

Try this instead:

class Back(object):    
    def square(self,x):
        y = x * x
        return y

def main():
    back = Back()
    print(back.square(3))


if __name__ == "__main__":
    main()

notice how main is defined at the root level (it's not indented like square). It's not part of the class this way and doesn't need self. You could make it a method of the Back class again like this:

classBack(object):    defsquare(self,x):
        y = x * x
        return y

    defmain(self):
        print(self.square(3))


if __name__ == "__main__":
    back = Back()
    back.main()

Ok, this last one, it doesn't really make sens to do it this way, I admit. But I'm just trying to illustrate scope and the difference between function and methods in python (I think this logic may help the OP more, considering the question).

Post a Comment for "Python Calling A Function From Another Function In A Class"