DEV Community

SyntaxFix
SyntaxFix

Posted on

Python global name 'self' is not defined

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()
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)