1. What is? property
Simply put, once a method in a class is @property decorate , You can call this method as you would call an attribute , It can simplify the process for the caller to obtain data , And don't worry about exposing properties , Someone assigned it ( Avoid unreasonable operation of users ). Two things to note
>>> class Goods():
def __init__(self,unit_price,weight):
self.unit_price = unit_price
self.weight = weight
@property
def price(self):
return self.unit_price * self.weight
>>> lemons = Goods(7,4)
>>>
>>> lemons.price
28
The above method directly calls to... By calling attributes price Method ,property Encapsulate the complex process into the method , Call the corresponding method name when getting the value .
2.property Two methods of attribute definition
A、 Decorator mode
Apply to the methods of a class @property Decorator , That is, the way above .
B、 Class attribute mode
Create an instance object to assign values to class properties
>>> class Lemons():
def __init__(self,unit_price=7):
self.unit_price = unit_price
def get_unit_price(self):
return self.unit_price
def set_unit_price(self,new_unit_price):
self.unit_price = new_unit_price
def del_unit_price(self):
del self.unit_price
x = property(get_unit_price, set_unit_price, del_unit_price)
>>> fruit = Lemons()
>>>
>>> fruit.x # call fruit.x Trigger get_unit_price
7
>>>
>>> fruit.x = 9 # call fruit.x = 9 Trigger set_unit_price
>>>
>>> fruit.x
9
>>>
>>> fruit.unit_price # call fruit.unit_price Trigger get_unit_price
9
>>> del fruit.x # call del fruit.x Trigger del_unit_price
>>>
>>> fruit.unit_price
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
l.unit_price
AttributeError: 'Lemons' object has no attribute 'unit_price'
property Method can accept four parameters
3. use property Instead of getter and setter Method
>>>class Watermelon():
def __init__(self,price):
self._price = price # Private property , External cannot be modified and accessed
def get_price(self):
return self._price
def set_price(self,new_price):
if new_price > 0:
self._price = new_price
else:
raise 'error: The price must be greater than zero '
use property Instead of getter and setter
>>>class Watermelon():
def __init__(self,price):
self._price = price
@property # Use @property decorate price Method
def price(self):
return self._price
@price.setter # Use @property Decoration method , When the price assignment , Call decoration method
def price(self,new_price):
if new_price > 0:
self._price = new_price
else:
raise 'error: The price must be greater than zero '
>>> watermelon = Watermelon(4)
>>>
>>> watermelon.price
4
>>>
>>> watermelon.price = 7
>>>
>>> watermelon.price
7