5
浅谈Python的property装饰器
source link: https://allenwind.github.io/blog/4800/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Mr.Feng Blog
NLP、深度学习、机器学习、Python、Go
浅谈Python的property装饰器
浅谈Python的property装饰器
Python的property装饰器
property装饰器可以装饰类的方法从而可以用属性访问来触发该方法,同时该方法带有getter和setter装饰器。
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/
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK