2013-02-08 94 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