2013-03-20 122 views
7

我注意到,雖然「最大」功能上無類型做好:的Python分鐘的無類型/最大

In [1]: max(None, 1) 
Out[1]: 1 

「分鐘」功能不返回任何內容:

In [2]: min(None, 1) 
In [3]: 

也許這是因爲min(沒有,1)沒有定義? 那麼爲什麼在最大的情況下,它返回數字? 是沒有對待'-infinity'?

回答

7

由於jamylak寫,None根本就沒有被Python炮彈打印。

這是方便,因爲所有函數返回的東西:沒有指定值時,他們返回None

>>> def f(): 
...  print "Hello" 
...  
>>> f() 
Hello 
>>> print f() # f() returns None! 
Hello 
None 

這就是爲什麼Python的彈不打印返回無值。但是,print None是不同的,因爲它明確要求Python打印None值。


至於比較,None認爲是負無窮。

Python 2的general rule是,無法以任何有意義的方式進行比較的對象在比較時不會引發異常,而是返回一些任意的結果。在CPython中,任意規則如下:

除數字以外的其他類型的對象按其類型 名稱排序;不支持正確比較的相同類型的對象按照其地址排序。

Python 3中引發一個例外,對於像1 > None非有意義的比較,並通過max(1, None)所做的比較。


如果您確實需要-infinity,Python會提供float('-inf')

+0

那麼,爲什麼max(None,1)返回1呢?它是任意的? – mclafee 2013-03-20 12:47:01

+1

請注意,此規則僅適用於Python 2.在Python 3中,它是固定的,並且您會得到一個有意義的錯誤消息'unorderable types:int() jamylak 2013-03-20 12:57:38

+1

@mclafee:'max(None,1)'確實沒有定義。我引用的CPython 2的「按類型命名的順序」規則似乎不適用於整數和None之間的比較,因爲「None」的類型是'NoneType',後面是'int' '。也許第二條規則適用,儘管(在一個測試中,我做了'id(1)> id(None)'爲'True')。 – EOL 2013-03-20 12:59:55

7

它返回的東西,蟒蛇外殼只是不打印None

>>> min(None, 1) 
>>> print min(None, 1) 
None 
-1

如果你真的想要的值總是會比較少比其他任何,你需要創建一個小類:

class ValueLessThanAllOtherValues(object): 
    def __cmp__(self, other): 
     return -1 

# really only need one of these 
ValueLessThanAllOtherValues.instance = ValueLessThanAllOtherValues() 

這個類會比較反對任何其他類型的值:

tiny = ValueLessThanAllOtherValues.instance 
for v in (-100,100,0,"xyzzy",None): 
    print v 
    print v > tiny 
    print tiny < v 
    # use builtins 
    print min(tiny,v) 
    print max(tiny,v) 
    # does order matter? 
    print min(v,tiny) 
    print max(v,tiny) 
    print 

打印:

-100 
True 
True 
<__main__.ValueLessThanAllOtherValues object at 0x2247b10> 
-100 
<__main__.ValueLessThanAllOtherValues object at 0x2247b10> 
-100 

100 
True 
True 
<__main__.ValueLessThanAllOtherValues object at 0x2247b10> 
100 
<__main__.ValueLessThanAllOtherValues object at 0x2247b10> 
100 

0 
True 
True 
<__main__.ValueLessThanAllOtherValues object at 0x2247b10> 
0 
<__main__.ValueLessThanAllOtherValues object at 0x2247b10> 
0 

xyzzy 
True 
True 
<__main__.ValueLessThanAllOtherValues object at 0x2247b10> 
xyzzy 
<__main__.ValueLessThanAllOtherValues object at 0x2247b10> 
xyzzy 

None 
True 
True 
<__main__.ValueLessThanAllOtherValues object at 0x2247b10> 
None 
<__main__.ValueLessThanAllOtherValues object at 0x2247b10> 
None 

微小的比自己還少!

print tiny < tiny 
True 
+0

你的'ValueLessThanAllOtherValues'比其他任何東西都小。例如,以相同的方式定義的任何其他類在放置在比較的左側時會生成較小的對象。原因是比較中* first *對象的'__cmp __()'被首先調用(所以'__cmp __()'可能不會被調用)。 – EOL 2013-03-20 14:20:40

+0

大跳蚤的背上有小跳蚤咬他們, 而小跳蚤只有較小的跳蚤,因此無窮無盡。 – PaulMcG 2013-03-20 14:31:14