The Wrapper class in Python

I want to have a wrapper class that behaves exactly like the object it wraps, except that it adds or overwrites multiple selected methods.

Currently my code looks like this:

# Create a wrapper class that equips instances with specified functions
def equipWith(**methods):

  class Wrapper(object):
    def __init__(self, instance):
      object.__setattr__(self, 'instance',instance)

    def __setattr__(self, name, value):
      object.__setattr__(object.__getattribute__(self,'instance'), name, value)

    def __getattribute__(self, name):
      instance = object.__getattribute__(self, 'instance')

      # If this is a wrapped method, return a bound method
      if name in methods: return (lambda *args, **kargs: methods[name](self,*args,**kargs))

      # Otherwise, just return attribute of instance
      return instance.__getattribute__(name)

  return Wrapper

      

To test this, I wrote:

class A(object):
  def __init__(self,a):
    self.a = a

a = A(10)
W = equipWith(__add__ = (lambda self, other: self.a + other.a))
b = W(a)
b.a = 12
print(a.a)
print(b.__add__(b))
print(b + b)

      

When on the last line my interpreter complains:

Traceback (most recent call last):
  File "metax.py", line 39, in <module>
    print(b + b)
TypeError: unsupported operand type(s) for +: 'Wrapper' and 'Wrapper'

      

Why is this? How can I get my wrapper class to behave the way I want?

+3


source to share


1 answer


It looks like what you want can only be done with new style objects with extraordinary measures. cm. fooobar.com/questions/225244 / ... , this blog post and.



Basically, "special" functions short-circuit the search procedure in new style objects.

+6


source







All Articles