我需要在Python中有一个等于所有数字的幻数,以便这样
magic_num == 20
magic_num == 300
magic_num == 10
magic_num == -40
我不希望这样的事情存在,但也许还有另一种方法可以做到这一点?
如果您确实想要,您可以创建一个可以与任何数字类型进行比较的类:
import numbers
class MagicNum:
def __eq__(self, other):
return isinstance(other, numbers.Number)
# To compare equal to other magic numbers too:
return isinstance(other, (numbers.Number, MagicNum))
然后创建一个实例:
magic_num = MagicNum()
我不确定您为什么要想要执行此操作(我怀疑是an XY problem,但可以。
您的意思是这样的吗?
class SuperInt(int):
def __eq__(self, other):
# This is not the correct approach, but I'm leaving it as it's what
# I wrote. ShadowRanger's answer is better given your requirement of
# matching any number.
return True
x = 5
y = SuperInt(3)
print(x == y) # -> True
print(x != y) # -> True
print(y != 3) # -> False
注意,后两个可能不是您想要的,因此您可能还需要覆盖__ne__
。更不用说其他comparison methods。