Nested objects and setattr & getattr (yes, that time)

Overview:

class Inner(object): def __init__(self, x): self.x = x class Outer(object): def __init__(self, z): self.inner = Inner(z) o = Outer(10) 

Now I want the Outer object to behave transparently - any attributes set to o should be set to o.inner , the same for reading: o.something should really return o.inner.sommething . A kind of proxy or relay.

__getattr__ for Outer seems simple and works:

 def __getattr__(self, item): return getattr(self, item) 

How do I handle __setattr__ ? I could not think of anything that would not cause a recursion error and make me hate.

Or is the concept itself erroneous?

(The other approach I tried was that Outer is a subclass of Inner - it really didn't play aesthetically true @classmethods , not to mention that the IDE would be lost inside them - would not be able to solve some attributes. Let me leave it now , perhaps?)

+6
source share
1 answer

The tricky part correctly sets the inner attribute of the Outer class. What you can do is call the __setattribute__ object method ( Outer base class):

 class Inner(object): def __init__(self, x): self.x = x class Outer(object): def __init__(self, z): object.__setattr__(self, 'inner', Inner(z)) def __getattr__(self, name): return getattr(self.inner, name) def __setattr__(self, name, value): return setattr(self.inner, name, value) 

Now it works correctly:

 o = Outer(10) print ox # 10 print o.inner.x # 10 og = 3 print og # 3 print o.inner.g # 3 

However, it is not clear to me why you do not want to use inheritance in this case. It seems more natural and pythonic to have Outer inherit from inner .

+7
source

Source: https://habr.com/ru/post/907864/


All Articles