drs*_*drs 6 python getter-setter python-decorators
我的课程有很多属性,都需要使用相同类型的setter:
@property
def prop(self):
return self._prop
@prop.setter
def prop(self, value):
self.other_dict['prop'] = value
self._prop = value
Run Code Online (Sandbox Code Playgroud)
是否有一种简单的方法可以将此setter结构应用于多个属性,而无需为每个属性编写这两种方法?
您可以使用描述符来实现这一点,即如下所示:
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
Run Code Online (Sandbox Code Playgroud)
并按如下方式使用它们:
class MyClass(object):
prop = MyProperty("prop")
another_prop = MyProperty("another_prop")
Run Code Online (Sandbox Code Playgroud)
附带说明:可能值得考虑是否真的需要复制属性值。_prop您可以通过从 中返回相应的值来轻松地完全摆脱该属性other_dict。这也避免了由于存储在字典和类实例中的不同值而引起的潜在问题 - 这在您当前的方案中很容易发生。