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
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.
In Python self
is the conventional name given to the first argument of instance methods of classes, which is always the instance the method was called on:
class A(object):
def f(self):
print self
a = A()
a.f()
Will give you something like
<__main__.A object at 0x02A9ACF0>
If you come from a language such as Java maybe you can make some kind of association between self
and this
. self
will be the reference to the object that called that method but you need to declare a class first. Try:
class MyClass(object)
def __init__(self)
#equivalent of constructor, can do initialisation and stuff
def setavalue(self):
self.myname = "harry"
def printaname(self):
print "Name", self.myname
def main():
#Now since you have self as parameter you need to create an object and then call the method for that object.
my_obj = MyClass()
my_obj.setavalue() #now my_obj is passed automatically as the self parameter in your method declaration
my_obj.printname()
if __name__ == "__main__":
main()
You can try some Python basic tutorial like here: Python guide
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With