0

I'm trying to make a class like Proxy that I indirectly access all methods of my objects, for example like:

class Radio():   
    def __init__(self):        
        self._channel = "channel"        

    def get_channel(self):        
        return self._channel    

    def set_channel(self, value):        
        self._channel = value   

class Proxy:
    def __init__(self, obj):        
        self.obj = obj

    # rest of the code
        


radio = Radio()
radio_proxy = Proxy(radio)
print(radio_proxy.get_channel())     

so this works exactly as print(radio.get_channel()) !!! but I'm actually stuck how to do this, I know that it's somehow I should use getattr and stuff but I don't really know how to use them

1 Answers1

0

You're almost there:

class Proxy:
    def __init__(self, obj):        
        self.obj = obj

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

This doesn't handle "dunder methods", ie. you can't do:

a = Proxy(5)
a + 37

but for regular methods (and attributes) it should be fine.

thebjorn
  • 26,297
  • 11
  • 96
  • 138