Reputation: 725
I am confused to a example of property from python cookbook.
class Person:
def __init__(self, first_name):
self.first_name = first_name
@property
def first_name(self):
return self._first_name
@first_name.setter
def first_name(self, value):
self._first_name = value
>>>people = Person('Tom')
>>>people.first_name
'Tom'
>>>people.first_name = 'Jack'
>>>people.first_name
'Jack'
When a instance is created, a argument assigns to self.first_name. However, it will return a value of self._first_name when getter property is called since self.first_name is distinguish to self._first_name. What is a relationship between self.first_name and self._first_name? How the two different variables related to each other?
Upvotes: 0
Views: 735
Reputation: 522480
self.first_name
/people.first_name
is the setter method-turned-property def first_name(self, value)
, while self._first_name
is the actual attribute holding the value. The constructor uses the setter to set the initial name, it doesn't directly assign to the property.
first_name
whichdef first_name
which_first_name
Note that there's another confusing typo in the constructor, it should be self.first_name = first_name
.
Upvotes: 1