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?
@properetydecorators make properties more clear: docs.python.org/2/library/functions.html#property -- Is your question how to define property functions are defined in subclasses? - ninMonkey@propertydecorator is equal tox = property(...)and using it does not change the behavior. I did not use it in the example as I wanted to be able to explicitly refer toset_xsetter. - Maciek D.propertyjust a very useful (and common) descriptor? - mgilson