2015-06-16 32 views
4

我的類有很多屬性,這些屬性都需要使用相同類型的二傳手:我可以對多個屬性使用相同的@property設置器嗎?

@property 
def prop(self): 
    return self._prop 

@prop.setter 
def prop(self, value): 
    self.other_dict['prop'] = value 
    self._prop = value 

是否有此setter結構應用到許多性質,不涉及寫這兩個簡單的方法每個屬性的方法?

回答

3

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

相關問題