python - 为什么 Python 允许比较可调用对象和数字?

标签 python

我上周用python写了一个作业,这里是代码片段

def departTime():
    '''
    Calculate the time to depart a packet.
    '''
    if(random.random < 0.8):
        t = random.expovariate(1.0 / 2.5)
    else:
        t = random.expovariate(1.0 / 10.5)
    return t

你能看出问题所在吗?我将 random.random 与 0.8 进行比较, 应该是 random.random()。

当然这是因为我的粗心,但我不明白。在我的 意见,这种比较至少应该引起警告 任何编程语言。

那么为什么 python 只是忽略它并返回 False?

最佳答案

这并不总是错误

首先,澄清一下,这不是总是的错误。

在这种特殊情况下,很明显比较是错误的。

但是,由于 Python 的动态特性,请考虑以下(即使糟糕,也完全有效)代码:

import random
random.random = 9 # Very weird but legal assignment.
random.random < 10 # True
random.random > 10 # False

比较对象时实际发生了什么?

至于您的实际情况,将函数对象与数字进行比较,请查看 Python 文档:Python Documentation: Expressions .查看标题为“比较”的第 5.9 节,其中指出:

The operators <, >, ==, >=, <=, and != compare the values of two objects. The objects need not have the same type. If both are numbers, they are converted to a common type. Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily. You can control comparison behavior of objects of non-built-in types by defining a cmp method or rich comparison methods like gt, described in section Special method names.

(This unusual definition of comparison was used to simplify the definition of operations like sorting and the in and not in operators. In the future, the comparison rules for objects of different types are likely to change.)

这应该可以解释发生的事情及其原因。

顺便说一句,我不确定在较新版本的 Python 中会发生什么。

编辑:如果您想知道,Debilski 的回答提供了有关 Python 3 的信息。

关于python - 为什么 Python 允许比较可调用对象和数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1778521/

相关文章:

python - Django 尝试但不工作

python - 基于线上方/下方组的阴影背景

python - python 3.2中的奇怪错误

python - Azure ML 包启动的 Tensorboard 无法正常工作

python - 在Python中对齐QMenuBar

python - pandas.to_datetime() 自动转换为 <M8[ns] 且无法使用 numpy.isnat()

python - 为什么在 Keras 中尝试构建具有多个输入的架构时会出错?

python - 按行打印字典

python - 如何在两个 float 之间插入运算符号并计算结果?

python - 独立于其他命令每 5 分钟运行一部分代码