为什么Python允许比较可调用和数字?

2024-09-30 00:31:36 发布

您现在位置: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

你能看出问题所在吗?我比较一下随机。随机0.8,即 应该是随机。随机(). 在

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

那么为什么python忽略它并返回False呢?在


Tags: theto代码returniftimepacketdef
3条回答

因为在Python中,这是一个非常有效的比较。Python不知道您是真的想进行这种比较,还是只是犯了一个错误。您的工作是为Python提供合适的对象进行比较。在

由于Python的动态特性,您可以将几乎所有内容与几乎所有内容进行比较和排序(这是一个特性)。在本例中,您将函数与float进行了比较。在

例如:

list = ["b","a",0,1, random.random, random.random()]
print sorted(list)

这将产生以下输出:

^{pr2}$

这并不总是一个错误

首先,为了弄清楚,这并不总是一个错误。在

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

但是,由于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的答案给出了关于Python3的信息。在

相关问题 更多 >

    热门问题