I want to make a wrapper class that behaves in exactly the same way as the wrapped object (with a few specific exceptions). The problem I’m having at the moment is with built-in functions. How could I redirect built-in functions to the wrapped object?
class Wrapper:
def __init__(self, wrapped):
object.__setattr__(self, '_wrapped', wrapped)
def __getattr__(self, name):
return getattr(object.__getattribute__(self, '_wrapped'), name)
class Foo:
def __init__(self, val):
self.val = val
def __abs__(self):
return abs(self.val)
foo = Wrapper(Foo(-1))
print(foo.val) # Okay
print(abs(foo)) # TypeError: bad operand type for abs(): 'Wrapper'
You can dynamically create a new class that is subclass of both
WrapperandFoo, so you’ll have all the properties needed:So now you can do:
PS:
object.__getattr__(or__setattr__) in the__init__and__getattr__functions to get and set this attribute.