2015-04-13 78 views
0

我需要在设置属性之前检查属性。一个天真的实施将是这样的:在设置属性之前检查属性的最佳方法是什么?

class C(object): 
    x = 5 

    def __setattr__(self, name, value): 
     if hasattr(self, name): 
      x = getattr(self, name) 

      if x == 5: 
       print 'do something' 
     object.__setattr__(self, name , value) 

然而,这会触发类__getattribute__方法,它必须来避免这里。从我所知道的情况来看,直接在班级'__dict__中搜索可能会诀窍;但是由于这是一个意图被用户分类的类,我想__slots__和MRO可能会增加复杂性。

鉴于这些考虑因素,在设置属性之前检查属性的最佳方法是什么?


在充分披露的利益,这个类实际上是要写成C延伸;不过,我并不认为这个策略偏离了python实现的重要性。

回答

1

怎么样使用property装饰者?

class C(object): 
    def __init__(self): 
     self._x = 5 # Default, for all 
     # Future updates should be done with self.x = ... 
     # To go through the approval below 

    @property 
    def x(self): 
     return self._x 
    @x.setter 
    def x(self, value): 
     if value == 5: 
      print 'do something' 
     else: 
      self._x = value 
相关问题