【问题标题】:Python - A magic number that is equal to all numbers?Python - 一个等于所有数字的幻数?
【发布时间】:2020-03-28 20:18:41
【问题描述】:

我需要一些 Python 中的幻数,它等于所有数字,以便

magic_num == 20
magic_num == 300
magic_num == 10
magic_num == -40

我不希望这样的事情存在,但也许有其他方法可以做到这一点?

【问题讨论】:

  • 要检查右边的表达式是否为数字? docs.python.org/3/library/stdtypes.html#str.isnumeric
  • @ShubhamSharma: str.isnumeric 是一个几乎没用的函数;它正在检查类似数字的字符串,但它实际上无法识别所有可解析为数字的字符串。通常,您无论如何都不想使用字符串,只需进行类型检查即可; numbers 模块中的 ABC 处理这种情况。
  • @ShadowRanger 是的,没错!虽然我想知道这个问题的最初动机是什么。

标签: python equality


【解决方案1】:

如果你真的想要,你可以创建一个比较等于任何数字类型的类:

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__

【讨论】:

  • 为什么需要数字库?而且这似乎是一个死项目,这让我想避免它。 github.com/jeanpimentel/numbers
  • @Vader:我们不是在谈论第三方包; numbersthe built-in module that contains the numeric tower ABCsnumbers.Number 是所有数字类型的虚拟超类(intfloatcomplexfractions.Fractiondecimal.Decimal 等都注册为它的子类)。
  • 关于 XY 问题,不确定是否是,但也许你可以告诉我。我有一个随时间变化的风向数据集。在风速非常低的某些时候,在这种情况下,风向是无关紧要的。所以当我比较昨天的风和今天的风,两者都是低风速时,我想说它们是一样的。
  • @Vader:你能把足够低的值刷新到 0 吗? if windspeed < LOW_THRESHOLD: windspeed = 0.
  • 我可以,但我更关注风向而不是风速。只是风速低时的风向是特例。
【解决方案2】:

你的意思是这样的吗?

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了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    • 2017-04-09
    • 1970-01-01
    • 1970-01-01
    • 2023-02-23
    • 2018-12-16
    • 2011-12-18
    相关资源
    最近更新 更多