簡體   English   中英

為什么我不能覆蓋這個魔術方法?

[英]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 中測試的)

特殊方法總是在實例的類型(這里是類對象) 上查找,而不是在實例上查找 否則,當您嘗試打印類本身的表示時,將使用類上的__repr__ type(class).__repr__(class)會使用正確的魔法方法,而class.__repr__()會引發異常,因為沒有提供self

您需要直接在包裝器上實現這些特殊方法,傳播在被包裝的對象上調用時可能引發的任何異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM