Alex G. Borrego
Alex G. Borrego

Reputation: 19

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

Upvotes: 0

Views: 8331

Answers (3)

LhasaDad
LhasaDad

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

cizixs
cizixs

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

Blownhither Ma
Blownhither Ma

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

Related Questions