pipi
pipi

Reputation: 725

How python variables name in getter and setter method are different to the name in its constructor?

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

Answers (1)

deceze
deceze

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.

  1. constructor receives value as function parameter
  2. constructor assigns to property first_name which
  3. invokes the setter def first_name which
  4. assigns to the property _first_name

Note that there's another confusing typo in the constructor, it should be self.first_name = first_name.

Upvotes: 1

Related Questions