I want to override the __setattr__
method on python classes using python 3.4.3. I found this answer but it does not seem to work as I get an error.
The full code is as follows:
class TestClass(object):
def __init__(self):
self.x = 4
def __setattr__(self, name, value):
# do something special given the 'name'
#default behavior below
super(TestClass).__setattr__(name, value)
test = TestClass()
and the error is
Traceback (most recent call last):
File "client_1.py", line 26, in <module>
test = TestClass()
File "client_1.py", line 17, in __init__
self.x = None
File "client_1.py", line 23, in __setattr__
super(TestClass).__setattr__(name, value)
AttributeError: 'super' object has no attribute 'x'
I assume the attribute x
cannot be set as it is not yet defined. And the line trying to define this atribute (in __init__
) cannot define the attribute, as it calls the overwritten method...
How to define the attribute x
without implicity calling the overwritten __setattr__
method then?