Reputation: 19
I'm getting this error quite often so I'd like to give an example:
class Me():
def __init__(self,name):
self.name=name
def call():
myname=Me("Alex")
printIt()
def printIt():
print(myname.name)
call()
Why am I getting this error instead of printing "Alex"? Thanks in advance
Upvotes: 0
Views: 8331
Reputation: 2143
myname is not a global variable. it is not in scope in the printIt method. it is local to the call method. if you want access to it, declare it in a way that it is global or pass the myname object as a parameter to printIt.
Upvotes: 0
Reputation: 13981
myname
is a local variable that can only be used inside function where it's defined.
try pass it as argument:
def call():
myname = Me("Alex")
printIt(myname)
def printIt(myname):
print(myname.name)
Upvotes: 1
Reputation: 1471
Variable defined in blocks has block-scope, which means they are not visible from outside. myname
is in function call
, and is only visible in call
.
If we follow your style
myname = None
def call():
global myname
myname = Me("Alex")
printIt()
def printIt(): # now we could access myname
print(myname.name)
However, a better choice is to avoid unnecessary globals by using
def call():
myname = Me("Alex")
printIt(myname)
def printIt(somebody): # now we could access aPerson as well
print(somebody.name)
Upvotes: 0