我想要一個包裝類,其行爲與它所包裝的對象完全相同,只是它添加或覆蓋了一些選擇方法。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'
這是爲什麼?我如何讓自己的包裝類以我想要的方式行事?
http://stackoverflow.com/questions/972/adding-a-method-to-an-existing-object我想這也可能是問題的一部分。 – tacaswell