简体   繁体   中英

NameError: name 'myname' is not defined in Python

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

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)

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM