While running this script I am receiving the following error.
p1=Person1("Plumber",fav_food,ethnicity,name,"male")
NameError: name 'fav_food' is not defined
I am new to OOP but, the way I understand it, fav_food
is define when I defined the Person1
class. Obviously I am wrong, but why?
class Person():
def __init__(self,job,fav_food,ethnicity,name,gender):
self.job=job
self.fav_food=fav_food
self.ethnicity=ethnicity
self.name=name
self.gender=gender
class Person1(Person):
def __init__(self,job,fav_food,ethnicity,name,gender):
Person.__init__(self,job,fav_food,ethnicity,name,gender)
self.job=job
self.fav_food="chips"
self.ethnicity="white"
self.name=random.shuffle(names)[0]
self.gender=gender
p1=Person1("Plumber",fav_food,ethnicity,name,"male")
remove all unnecessary arguments from Person1.__init__
:
class Person():
def __init__(self, job,fav_food,ethnicity,name,gender):
self.job=job
self.fav_food=fav_food
self.ethnicity=ethnicity
self.name=name
self.gender=gender
class Person1(Person):
def __init__(self,job,gender):
Person.__init__(self,job,"chips","white",random.shuffle(names)[0],gender)
p1=Person1("Plumber", "male")
fav_food
is defined locally in __init__
and in future instance namespaces due to its sole assignment in __init__
. It is not defined in the module namespace in which you attempt to create a Person1
instance using fav_food
, hence the error.
Python uses the LEGB rule for variable name resolution. It searches from L to B, starting at the level in which the name occurs. The name resolves to the first name definition found. A NameError occurs if no name definition is found.
L - Local : first it looks for variable definitions in the local scope of functions
E - Enclosing : next it looks in the scope of any enclosing functions
G - Global : then it looks for the variable definition at the module level. In the code fav_food
is referenced in the module scope, so Python requires a definition of fav_food
at the module level or higher
B - Built-in : finally Python looks for built-in variable definitions
In addition to LEGB name resolution, there is also object.attribute resolution. In this case fav_food
will be defined in person instances: person.fav_food
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.