【问题标题】:Can I use the same @property setter for multiple properties?我可以对多个属性使用相同的 @property 设置器吗?
【发布时间】:2015-09-01 07:25:15
【问题描述】:
我的类有许多属性都需要使用相同类型的 setter:
@property
def prop(self):
return self._prop
@prop.setter
def prop(self, value):
self.other_dict['prop'] = value
self._prop = value
有没有一种简单的方法可以将此 setter 结构应用于许多属性,而不涉及为每个属性编写这两种方法?
【问题讨论】:
标签:
python
getter-setter
python-decorators
【解决方案1】:
您可以使用descriptor 来实现这一点,即如下:
class MyProperty(object):
def __init__(self, name):
self.name = name
def __get__(self, instance, owner):
if instance is None:
return self
else:
# get attribute from the instance
return getattr(instance, '_%s' % self.name) # return x._prop
def __set__(self, instance, value):
# set attribute and the corresponding key in the "remote" dict
instance.other_dict[self.name] = value # x.other_dict["prop"] = value
setattr(instance, '_%s' % self.name, value) # x._prop = value
并按如下方式使用它们:
class MyClass(object):
prop = MyProperty("prop")
another_prop = MyProperty("another_prop")
附带说明:您是否真的需要复制属性值可能值得考虑。通过从other_dict 返回相应的值,您可以轻松地完全摆脱_prop 属性。这也避免了由存储在 dict 和类实例中的不同值引起的潜在问题——这很容易在您当前的方案中发生。