2013-02-08 56 views
3

我想要一个包装类,其行为与它所包装的对象完全相同,只是它添加或覆盖了一些选择方法。Python中的包装类

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

# 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' 

这是为什么?我如何让自己的包装类以我想要的方式行事?

+0

http://stackoverflow.com/questions/972/adding-a-method-to-an-existing-object我想这也可能是问题的一部分。 – tacaswell

回答

6

它看起来像你想要的只能用非常措施的新式对象来完成。见https://stackoverflow.com/a/9059858/380231this blog postdocumentation

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

+0

你认为什么是错上https://stackoverflow.com/questions/9057669/how-can-i-intercept-calls-to-pythons-magic-methods-in-new-style-classes –

+0

顶端回答更新了该链接。当我回答这个问题时绝对不知道元类。 – tacaswell