Tips for using property in Python
- 2021-12-04 19:08:36
- OfStack
property Properties
A special property that works like using instance property 1 and can correspond to a method
It is necessary to protect the encapsulation characteristics of classes and let developers use objects. Attributes to manipulate methods,
@property 装饰器
You can access the method directly through the method name without adding a pair of
()
Parentheses.
Let's look at an example of finding the area of a circle
class Circle(object):
PI = 3.14
def __init__(self, r):
# r The radius of a circle
self.r = r
self.__area = self.PI * self.r * self.r
@property
def area(self):
return self.__area
def get_area(self):
return self.__area
In [2]: c = Circle(10)
In [3]: c.area
Out[3]: 314.0
In [4]: c.get_area()
Out[4]: 314.0
The definition and invocation of property attributes should pay attention to the following points:
When defined, add on top of the instance method@property
Decorator; And only one
self
Parameter
Called without parentheses
()
Instance method: c.get_area()
property Method of decoration: c.area
Specific examples
For a list page of computer hosts displayed in a shopping mall, it is impossible to display all the contents in the database on the page every time a request is made, but it is displayed locally through the paging function. Therefore, when requesting data from the database, the specified acquisition to be displayed is obtained from the
m
Articles to articles
n
The functions of this paging include:
class Pager(object):
def __init__(self, current_page):
# The page number currently requested by the user (page 1 Page, p 2 Page ... )
self.current_page = current_page
# Default display per page 10 Bar data
self.per_items = 10
@property
def start(self):
val = (self.current_page - 1) * self.per_items
return val
@property
def end(self):
val = self.current_page * self.per_items
return val
# ipython Test
In [2]: p = Pager(1)
In [3]: p.start # Is the starting value, that is: m
Out[3]: 0
In [4]: p.end # Is the end value, that is: n
Out[4]: 10
In [5]: p = Pager(2)
In [6]: p.start
Out[6]: 10
In [7]: p.end
Out[7]: 20
There are two ways for the property attribute
Decorator is: applying decorator in method@property
Class attributes are: defined in the class with a value of
property
Class properties of an object
property()
Decorator mode
Applied to the instance method of the class
@property
Decorator
The classes in Python are
旧式类
And
新式类
,
新式类
Attribute ratio of
旧式类
The attribute of is rich.
Old-style class
Old-style class with 1 kind
@property
Decorator
class Goods:
def __init__(self, name):
self.name = name
@property
def price(self):
return 100
# ipython Test
In [10]: g = Goods(' Watches ')
In [11]: g.price
Out[11]: 100
New class
New class, with 3 kinds
@property
Decorator
class Goods:
"""
python3 Default inheritance in object Class
With python2 , 3 The result of executing this program is different, because only in the python3 Only in @xxx.setter @xxx.deleter
"""
@property
def price(self):
print('@property')
@price.setter
def price(self, value):
print('@price.setter')
@price.deleter
def price(self):
print('@price.deleter')
# ipython Test
In [13]: g = Goods()
In [14]: g.price
@property
In [15]: g.price = 100
@price.setter
In [16]: del g.price
@price.deleter
g.price
Individual call auto-execution
@property
Modified
price
Method and get the return value of the method
g.price = 100
Assignment auto-execution
@price.setter
Modified
price
Method and set the
100
Parameters assigned to the method
del g.price
Delete auto-execution
@price.deleter
Modified
price
Method
Attention
There is only one way to access attributes in the old class, which corresponds to the@property
Method of modification
Attributes in the new class are accessed in three ways, and each corresponds to three attributes that are
@property
,
@方法名.setter
,
self
0
Method of modification
Because there are three access methods in the new class, we can define three methods as getting, modifying and deleting the same attribute according to their access characteristics.
# Goods Class @property Application
class Goods(object):
def __init__(self, name, price):
# Original price
self.original_price = price
# Discount
self.discount = 0.8
@property
def price(self):
# Actual price = Original price * Discount
new_price = self.original_price * self.discount
return new_price
@price.setter
def price(self, value):
self.original_price = value
@price.deleter
def price(self):
print(' Delete the original price of goods ')
del self.original_price
# ipython Test
In [22]: g = Goods(' Millet mobile phone ', 2000)
In [23]: g.price
Out[23]: 1600.0
In [24]: g.price = 3000
In [25]: g.price
Out[25]: 2400.0
In [26]: del g.price
Delete the original price of goods
In [27]: g.price
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-27-38ee45b469f2> in <module>
----> 1 g.price
<ipython-input-18-d5ea66eb7ece> in price(self)
12 def price(self):
13 # Actual price = Original price * Discount
---> 14 new_price = self.original_price * self.discount
15 return new_price
16
AttributeError: 'Goods' object has no attribute 'original_price'
Class attribute mode
Creates a value of
property
Class properties of the object, when creating the class properties
property
Property when the,
旧式类
And
新式类
No difference
class Foo:
def get_bar(self):
return 'get_bar'
BAR = property(get_bar)
# ipython Test
In [32]: f = Foo()
In [33]: f.BAR
Out[33]: 'get_bar'
f.BAR
Automatic call
get_bar()
Method and get the return value of the method
property()
There are 4 parameters in the
class Foo(object):
def __init__(self, bar):
self.bar = bar
def get_bar(self):
print('get_bar')
return self.bar
def set_bar(self, value):
""" You must have two parameters """
print('set bar ' + value)
self.bar = value
def del_bar(self):
print('del bar')
del self.bar
BAR = property(get_bar, set_bar, del_bar, "bar description...")
# ipython Test
In [50]: f = Foo('python')
In [51]: f.BAR
get_bar
Out[51]: 'python'
In [52]: f.BAR = 'Java'
set bar Java
In [53]: f.BAR
get_bar
Out[53]: 'Java'
In [54]: del f.BAR
del bar
property object versus @ property decorator
Created as a result of class attributes
property
Object attributes have three access methods. According to the access characteristics of several attributes, we can define three methods as accessing the same attribute: obtaining, modifying, deleting, and following
@property
Comparison of decorators.
property Object Class Properties
# Goods Class property Object class properties Application
class Goods(object):
def __init__(self, name, price):
# Original price
self.original_price = price
# Discount
self.discount = 0.8
def get_price(self):
# Actual price = Original price * Discount
new_price = self.original_price * self.discount
return new_price
def set_price(self, value):
self.original_price = value
def del_price(self):
print(' Delete the original price of goods ')
del self.original_price
PRICE = property(get_price, set_price, del_price, "price description")
# ipython Test
In [59]: g = Goods('Mac Computer ', 9000)
In [60]: g.PRICE
Out[60]: 7200.0
In [61]: g.PRICE = 10000
In [62]: g.PRICE
Out[62]: 8000.0
In [63]: del g.PRICE
Delete the original price of goods
@ property Decorator
# Goods Class @property Decorator Application
class Goods(object):
def __init__(self, name, price):
# Original price
self.original_price = price
# Discount
self.discount = 0.8
@property
def price(self):
# Actual price = Original price * Discount
new_price = self.original_price * self.discount
return new_price
@price.setter
def price(self, value):
self.original_price = value
@price.deleter
def price(self):
print(' Delete the original price of goods ')
del self.original_price
# ipython Test
In [59]: g = Goods('Mac Computer ', 9000)
In [60]: g.PRICE
Out[60]: 7200.0
In [61]: g.PRICE = 10000
In [62]: g.PRICE
Out[62]: 8000.0
In [63]: del g.PRICE
Delete the original price of goods
It can be found that both can be realized, but
@property
In the old class, only the
@property
, no
@method.setter
And
@method.deleter
And the new class can use both. Therefore, depending on everyone's habits, choose one.
Nature created our real world in tens of billions of years, while programmers created a completely different virtual world in hundreds of years. We use the keyboard to knock out 1 brick and 1 tile, and use the brain to build 1 cut. People regard 1000 as authority, but we do the opposite and defend the status of 1024. We are not keyboard men, we are just extraordinary creators in the ordinary world.