gpt4 book ai didi

python - 运行时重载运算符

转载 作者:行者123 更新时间:2023-12-01 03:39:29 27 4
gpt4 key购买 nike

是否可以在运行时重载运算符?我尝试了以下代码示例:

class A():
pass
a = A()
a.__eq__ = lambda self, other: False
a == a # this should return False since the __eq__-method should be overloaded but it returns
# True like object.__eq__ would
a.__eq__(a, a) # this returns False just as expected

为什么这段代码不起作用?是否有可能实现预期的行为?

最佳答案

魔术/双下划线方法是在类上查找的,而不是在实例上查找的。所以你需要重写类的方法,而不是实例。有两种方法可以做到这一点。

直接分配给类:

class A:
pass

a = A()
A.__eq__ = lambda self, other: False
print(a == a)
print(a.__eq__(a)) # You're already passing in self by calling it as an instance method, so you only pass in the other one.

或者,如果您只有实例并且使用的是 3.x,则可以执行以下操作:

class A:
pass

a = A()
type(a).__eq__ = lambda self, other: False
print(a == a)
print(a.__eq__(a))

关于python - 运行时重载运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39878667/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com