Python中的包装类

时间:2013-02-08 04:47:14

标签: python wrapper

我希望有一个包装类,它的行为与它包装的对象完全相同,只不过它会添加或覆盖一些select方法。

我的代码目前看起来像这样:

# 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

为了测试这个,我写道:

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)

在最后一行,我的翻译抱怨:

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

这是为什么?如何让我的包装器类按照我想要的方式运行?

1 个答案:

答案 0 :(得分:6)

看起来你想要的东西只能用非常规的新风格对象来完成。请参阅https://stackoverflow.com/a/9059858/380231this blog postdocumentation

基本上,'特殊'功能会使新式对象的查找过程短路。