python global name 'self' is not defined

harry picture harry · Aug 11, 2011 · Viewed 116.5k times · Source

Just started learning python and I am sure its a stupid question but I am trying something like this:

    def setavalue(self):
        self.myname = "harry"

    def printaname():
        print "Name", self.myname     

    def main():
        printname()




    if __name__ == "__main__":
        main() 

The error I am getting is:

 NameError: global name 'self' is not defined

I saw this way of using the self statement to reference variables of different methods in some code I read that is working fine.

Thanks for the help

Answer

Jacob picture Jacob · Aug 11, 2011

self is the self-reference in a Class. Your code is not in a class, you only have functions defined. You have to wrap your methods in a class, like below. To use the method main(), you first have to instantiate an object of your class and call the function on the object.

Further, your function setavalue should be in __init___, the method called when instantiating an object. The next step you probably should look at is supplying the name as an argument to init, so you can create arbitrarily named objects of the Name class ;)

class Name:
    def __init__(self):
        self.myname = "harry"

    def printaname(self):
        print "Name", self.myname     

    def main(self):
        self.printaname()

if __name__ == "__main__":
    objName = Name()
    objName.main() 

Have a look at the Classes chapter of the Python tutorial an at Dive into Python for further references.