python標准庫介紹——8 operator 模塊詳解


==operator 模塊==


``operator`` 模塊為 Python 提供了一個 "功能性" 的標准操作符接口. 當使用 ``map`` 以及 
``filter`` 一類的函數的時候, ``operator`` 模塊中的函數可以替換一些 ``lambda`` 函式. 
而且這些函數在一些喜歡寫晦澀代碼的程序員中很流行. [Example 1-62 #eg-1-62] 展示了 
``operator`` 模塊的一般用法.

====Example 1-62. 使用 operator 模塊====[eg-1-62]

```
File: operator-example-1.py

import operator

sequence = 1, 2, 4

print "add", "=>", reduce(operator.add, sequence)
print "sub", "=>", reduce(operator.sub, sequence)
print "mul", "=>", reduce(operator.mul, sequence)
print "concat", "=>", operator.concat("spam", "egg")
print "repeat", "=>", operator.repeat("spam", 5)
print "getitem", "=>", operator.getitem(sequence, 2)
print "indexOf", "=>", operator.indexOf(sequence, 2)
print "sequenceIncludes", "=>", operator.sequenceIncludes(sequence, 3)

*B*add => 7
sub => -5
mul => 8
concat => spamegg
repeat => spamspamspamspamspam

getitem => 4
indexOf => 1
sequenceIncludes => 0*b*
```

[Example 1-63 #eg-1-63] 展示了一些可以用於檢查對象類型的 ``operator`` 函數.

====Example 1-63. 使用 operator 模塊檢查類型====[eg-1-63]

```
File: operator-example-2.py

import operator
import UserList

def dump(data):
    print type(data), "=>",
    if operator.isCallable(data):
        print "CALLABLE",
    if operator.isMappingType(data):
        print "MAPPING",
    if operator.isNumberType(data):
        print "NUMBER",
    if operator.isSequenceType(data):
        print "SEQUENCE",
    print
        
dump(0)
dump("string")
dump("string"[0])
dump([1, 2, 3])
dump((1, 2, 3))
dump({"a": 1})
dump(len) # function 函數
dump(UserList) # module 模塊
dump(UserList.UserList) # class 類
dump(UserList.UserList()) # instance 實例

*B*<type 'int'> => NUMBER
<type 'string'> => SEQUENCE
<type 'string'> => SEQUENCE
<type 'list'> => SEQUENCE
<type 'tuple'> => SEQUENCE
<type 'dictionary'> => MAPPING
<type 'builtin_function_or_method'> => CALLABLE
<type 'module'> =>
<type 'class'> => CALLABLE
<type 'instance'> => MAPPING NUMBER SEQUENCE*b*
```

這里需要注意 ``operator`` 模塊使用非常規的方法處理對象實例. 所以使用 
``isNumberType`` , ``isMappingType`` , 以及 ``isSequenceType`` 函數的時候要小心, 
這很容易降低代碼的擴展性.

同樣需要注意的是一個字符串序列成員 (單個字符) 也是序列. 所以當在遞歸函數使用 isSequenceType 來截斷對象樹的時候, 別把普通字符串作為參數(或者是任何包含字符串的序列對象).

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM