In Python class, when I use __setattr__
it takes precedence over properties defined in this class (or any base classes). Consider the following code:
class Test(object):
def get_x(self):
x = self._x
print "getting x: %s" % x
return x
def set_x(self, val):
print "setting x: %s" % val
self._x = val
x = property(get_x, set_x)
def __getattr__(self, a):
print "getting attr %s" % a
return -1
def __setattr__(self, a, v):
print "setting attr %s" % a
When I create the class and try to set x
, __setattr__
is called instead of set_x
:
>>> test = Test()
>>> test.x = 2
setting attr x
>>> print test.x
getting attr x_
getting x: -1
-1
What I want to achieve is that the actual code in __setattr__
were called only if there is no relevant property i.e. test.x = 2
should call set_x
. I know that I can achieve this easily by manually checking if a
is "x" is __setattr__
, however this would make a poor design. Is there a more clever way to ensure the proper behavior in __setattr__
for every property defined in the class and all the base classes?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…