您可以實現此使用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
屬性。這也可以避免由字典和類實例中存儲的不同值引起的潛在問題 - 這可能很容易發生在您當前的方案中。