Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When accessing Properties, send to another instance

Tags:

python

class x():
    def __init__(self):
        self.z=2

class hi():
    def __init__(self):
        self.child=x()

f=hi()
print f.z

I want it to print 2.

Basically I want to forward any calls to that class to another class.

like image 968
user1513192 Avatar asked Sep 09 '26 21:09

user1513192


1 Answers

The simplest approach is implementing __getattr__:

class hi():
    def __init__(self):
        self.child=x()

    def __getattr__(self, attr):
        return getattr(self.child, attr)

This has certain disadvantages, but it might work for your limited use case. You might want to implement __hasattr__ and __setattr__ as well.

like image 105
Niklas B. Avatar answered Sep 11 '26 09:09

Niklas B.