Python calling a function from another function in a class

Viewed 2661

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 within class? and added self, but this didn't help. Here is the code, can anyone please point out the reason.

class Back(object):    

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


    def main():
        self.square(3)


    if __name__ == "__main__":
    main()

And I am calling it using python square.py

1 Answers

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

    def main(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:

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

    def main(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).

Related