2009-11-22 24 views
2

我用蟒蛇上周写的分配,这里是一个代码段为什么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呢?

回答

9

这并不总是一个错误

首先,只是为了把事情说清楚,这不是总是一个错误。

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

然而,由于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

3

因为在Python中是完全有效的比较。 Python无法知道你是否真的想进行比较,或者你是否犯了一个错误。向Python提供正确的对象以进行比较是您的工作。

由于Python的动态特性,您可以比较几乎所有东西并对几乎所有东西进行排序(这是一项功能)。在这种情况下,您已经将函数与浮点数进行了比较。

一个例子:

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

这会给以下输出:

[0, 0.89329568818188976, 1, <built-in method random of Random object at 0x8c6d66c>, 'a', 'b'] 
+1

你不能比较和排序*一切*。尝试排序复杂的数字,你会得到'TypeError:没有为复数定义的顺序关系。 – 2009-11-22 19:31:53

1

我认为Python允许这是因为random.random对象可以通过包括__gt__方法来重写>操作者在可能接受甚至期待一个数字的对象中。所以,python认为你知道你在做什么,并不报告它。

如果你尝试检查它,你可以看到,__gt__存在random.random ...

>>> random.random.__gt__ 
<method-wrapper '__gt__' of builtin_function_or_method object at 0xb765c06c> 

但是,这可能不是你想要做的事。

+0

我不认为'__gt__'需要定义,以便Python允许在不同类型之间进行比较大的比较 – 2009-11-22 12:38:38

+0

这是真的,这不是必要的,但我想表明它存在random.random无论如何。 – 2009-11-22 12:52:32