Python - 一个等于所有数字的幻数?
Python - A magic number that is equal to all numbers?
我需要 Python 中的某个幻数,它等于所有数字,这样
magic_num == 20
magic_num == 300
magic_num == 10
magic_num == -40
我不希望存在这样的事情,但也许有另一种方法可以做到这一点?
如果你真的想要,你可以创建一个 class 来比较等于任何数字类型:
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 MagicNum:
def __eq__(self, other):
return isinstance(other, numbers.Number)
# To compare equal to other magic numbers too:
return isinstance(other, (numbers.Number, MagicNum))
__le__ = __ge__ = __eq__
def __lt__(self, other):
return False
__gt__ = __lt__
你的意思是这样的吗?
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.
我需要 Python 中的某个幻数,它等于所有数字,这样
magic_num == 20
magic_num == 300
magic_num == 10
magic_num == -40
我不希望存在这样的事情,但也许有另一种方法可以做到这一点?
如果你真的想要,你可以创建一个 class 来比较等于任何数字类型:
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 MagicNum:
def __eq__(self, other):
return isinstance(other, numbers.Number)
# To compare equal to other magic numbers too:
return isinstance(other, (numbers.Number, MagicNum))
__le__ = __ge__ = __eq__
def __lt__(self, other):
return False
__gt__ = __lt__
你的意思是这样的吗?
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.