[英]Why Can't I Override this Magic Method?
我正在制作一個包裝對象,該對象將采用任意類的實例,然后自動包裝所有自己的魔術方法,以簡單地使用包裝對象的魔術方法(和值)。 出於某種原因,這不起作用:
class Wrapper:
def __init__(self, wrapped):
self.wrapped = wrapped
for method in filter(lambda x: x.startswith("__") and (x not in
["__init__", "__new__", "__class__", "__metaclass__"]),
dir(wrapped)):
if hasattr(getattr(wrapped, method), "__call__"):
new_func = functools.partial(getattr(type(wrapped), method), self.wrapped)
setattr(self, method, new_func)
t = Wrapper(7)
t + 8
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'Wrapper' and 'int'
class Tester:
def __init__(self):
self.v = 5
def __add__(self, other):
return self.v + other
y = Tester()
y + 7
12
t = Wrapper(y)
t + 9
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'Wrapper' and 'int'
9 + t
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'Wrapper'
t.__add__
functools.partial(<function Tester.__add__ at 0x7fbec6372170>, <__main__.Tester object at 0x7fbec6392990>)
t.__add__(7)
12
我想也許由於類型方法和實例方法之間的區別,部分無法正常工作,但是當我直接調用我的包裝器的魔術添加時,它可以正常工作。 (這是在 CPython 3.3 中測試的)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.