Here is my code
class Person:
def __init__(self, name, age):
self._name = name
self._age = age
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
@property
def age(self):
return self._age
@age.setter
def age(self, value):
self._age = age
person = Person("Alice", 30)
print(person.name) # "Alice"
person.name = "Bob"
print(person.name) # "Bob"
person.age = 32
And I get the error
`NameError: name 'age' is not defined`
How is it that I can set the name attribute just fine using a getter and a setter but doing the same thing with age doesn't work?
CodePudding user response:
Issue is your parameter name is value, but you are trying to find age, to fix this
class Person:
def __init__(self, name, age):
self._name = name
self._age = age
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
@property
def age(self):
return self._age
@age.setter
def age(self, age):
self._age = age
CodePudding user response:
class Person:
def __init__(self, name, age):
self._name = name
self._age = age
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
@property
def age(self):
return self._age
@age.setter
def age(self, value):
self._age = value #(before -> self._age = age)
person = Person("Alice", 30)
print(person.name) # "Alice"
person.name = "Bob"
print(person.name) # "Bob"
person.age = 32
print(person.age) #32