浅谈Python的property装饰器

Python的property装饰器

property装饰器可以装饰类的方法从而可以用属性访问来触发该方法,同时该方法带有getter和setter装饰器。

举例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

class Resistor(object):
def __init__(self, ohms):
self.ohms = ohms
self.voltage = 0
self.current = 0

class VoltageResistance(Resistor):
def __init__(self, ohms):
super().__init__(ohms)
self._valtage = 0

@property
def voltage(self):
return self._valtage

@voltage.setter
def voltage(self, voltage):
self._voltage = voltage
self.current = self._voltage / self.ohms

class BoundedResistance(Resistor):
def __init__(self, ohms):
super().__init__(ohms)

@property
def ohms(self):
return self._ohms

@ohms.setter
def ohms(self, ohms):
if ohms <= 0: # 控制属性的值范围或限制属性的修改
raise ValueError("%f ohms must be > 0" % ohms)
self._ohms = ohms

class FixedResistance(Resistor):
@property
def ohms(self):
return self._ohms

@ohms.setter
def ohms(self, ohms):
if hasattr(self, '_ohms'):
raise AttributeError("Can't set attribute")
self._ohms = ohms

转载请包括本文地址:https://allenwind.github.io/blog/4800
更多文章请参考:https://allenwind.github.io/blog/archives/