I am trying to change setattr and getattr methods in my class, but i have got an error when i am trying to define both of them.
class Basee:
def __init__(self, app):
self.app = app
self.x = 3
def test(self):
return self.x
def __getattr__(self, item):
if item in dir(self):
return getattr(self, item)
elif item in dir(self.app):
return getattr(self.app, item)
else:
if item in self.__dict__:
return self.__dict__[item]
else:
return self.app.__dict__[item]
class App:
def __init__(self, y):
self.y = y
def test2(self):
return self.y
app = App(5)
test = Basee(app)
Above code with only getattr works fine.
class Basee:
def __init__(self, app):
self.app = app
self.x = 3
def test(self):
return self.x
def __getattr__(self, item):
if item in dir(self):
return getattr(self, item)
elif item in dir(self.app):
return getattr(self.app, item)
else:
if item in self.__dict__:
return self.__dict__[item]
else:
return self.app.__dict__[item]
def __setattr__(self, key, value):
if key in self.__dict__:
return self.__setattr__(key, value)
else:
return self.app.__setattr__(key, value)
class App:
def __init__(self, y):
self.y = y
def test2(self):
return self.y
app = App(5)
test = Basee(app)
Above code with both methods raise and error:
Traceback (most recent call last):
File "C:\Program Files\Python37\lib\site-packages\IPython\core\interactiveshell.py", line 3326, in
run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-41-5e27f0c3b3cf>", line 8, in <module>
test = Basee(app)
File "<ipython-input-40-eff8d695cb0e>", line 3, in __init__
self.app = app
File "<ipython-input-40-eff8d695cb0e>", line 24, in __setattr__
return self.app.__setattr__(key, value)
File "<ipython-input-40-eff8d695cb0e>", line 12, in __getattr__
elif item in dir(self.app):
File "<ipython-input-40-eff8d695cb0e>", line 12, in __getattr__
elif item in dir(self.app):
File "<ipython-input-40-eff8d695cb0e>", line 12, in __getattr__
elif item in dir(self.app):
[Previous line repeated 1486 more times]
File "<ipython-input-40-eff8d695cb0e>", line 10, in __getattr__
if item in dir(self):
RecursionError: maximum recursion depth exceeded while calling a Python object
How can I repair it? I want to get and set all methods and atribitues of Base and App class by refereing to Base class, for example writing: test.y =7 should change in the code backgorund self.app.y on 7 then when I try to get test.y i can see 7 and it refer to self.app.y :-) Any ideas?