Using self.cost = cost in __init__ ,we are getting following output
inside __init__
inside setter
inside property
100
Using self._cost = cost in __init__ ,we are getting following output
inside __init__
inside property
100
In the first point,inside setter is being called but not in point 2.
class Book(object): def __init__(self,cost): print('inside __init__') self.cost = cost #self._cost = cost @property def cost(self): print('inside property') return self._cost @cost.setter def cost(self,value): print('inside setter') self._cost = value book = Book(100) print(book.cost)
It's not private vs. public, but your property name is cost
so self.cost = cost
triggers the property setter, but self._cost
does not, because there is no property _cost
. It will just assign new attribute _cost
.
Hope this code makes it clear for you. There are few things to be considered, the decorator name should match exactly with the member variable cost
or _cost
. Also, the return should be _variablename
. So if your variable name is _cost
, you must return __cost
.
class Book_(object):
def __init__(self,cost):
print('inside __init__')
self._cost = cost
@property
def _cost(self):
print('inside property')
return self.__cost
@_cost.setter
def _cost(self,value):
print('inside setter')
self.__cost = value
class Book(object):
def __init__(self,cost):
print('inside __init__')
self.cost = cost
@property
def cost(self):
print('inside property')
return self._cost ## see the difference with above
@cost.setter ## see the difference with above
def cost(self,value):
print('inside setter')
self._cost = value ## see the difference with above
book = Book(10)
print(book.cost)
print('---')
book2 = Book_(100)
print(book2._cost)
Output:
inside __init__
inside setter
inside property
10
---
inside __init__
inside setter
inside property
100
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.