### 2. 內建函數
Python解釋器內置了一些函數,它們總是可用。這里將它們按字母順序列出。
| | | Built-in Functions | | |
|-----|-----|-----|-----|-----|
| [abs()](# "abs") | [divmod()](# "divmod") | [input()](# "input") | [open()](# "open") | [staticmethod()](# "staticmethod") |
| [all()](# "all") | [enumerate()](# "enumerate") | [int()](# "int") | [ord()](# "ord") | [str()](# "str") |
| [any()](# "any") | [eval()](# "eval") | [isinstance()](# "isinstance") | [pow()](# "pow") | [sum()](# "sum") |
| [basestring()](# "basestring") | [execfile()](# "execfile") | [issubclass()](# "issubclass") | [print()](# "print") | [super()](# "super") |
| [bin()](# "bin") | [file()](# "file") | [iter()](# "iter") | [property()](# "property") | [tuple()](# "tuple") |
| [bool()](# "bool") | [filter()](# "filter") | [len()](# "len") | [range()](# "range") | [type()](# "type") |
| [bytearray()](# "bytearray") | [float()](# "float") | [list()](# "list") | [raw_input()](# "raw_input") | [unichr()](# "unichr") |
| [callable()](# "callable") | [format()](# "format") | [locals()](# "locals") | [reduce()](# "reduce") | [unicode()](# "unicode") |
| [chr()](# "chr") | [frozenset()](#) | [long()](# "long") | [reload()](# "reload") | [vars()](# "vars") |
| [classmethod()](# "classmethod") | [getattr()](# "getattr") | [map()](# "map") | [repr()](#) | [xrange()](# "xrange") |
| [cmp()](# "cmp") | [globals()](# "globals") | [max()](# "max") | [reversed()](# "reversed") | [zip()](# "zip") |
| [compile()](# "compile") | [hasattr()](# "hasattr") | [memoryview()](#) | [round()](# "round") | [__import__()](# "__import__") |
| [complex()](# "complex") | [hash()](# "hash") | [min()](# "min") | [set()](#) | [apply()](# "apply") |
| [delattr()](# "delattr") | [help()](# "help") | [next()](# "next") | [setattr()](# "setattr") | [buffer()](# "buffer") |
| [dict()](#) | [hex()](# "hex") | [object()](# "object") | [slice()](# "slice") | [coerce()](# "coerce") |
| [dir()](# "dir") | [id()](# "id") | [oct()](# "oct") | [sorted()](# "sorted") | [intern()](# "intern") |
abs(*x*)
返回一個數的絕對值。參數可以是普通的整數,長整數或者浮點數。如果參數是個復數,返回它的模。
all(*iterable*)
如果*iterable*的所有元素為真(或者iterable為空), 返回True。等同于:
~~~
def all(iterable):
for element in iterable:
if not element:
return False
return True
~~~
添加于版本2.5。
any(*iterable*)
如果*iterable*的任一元素為真,返回True。如果iterable為空,返回False。等同于:
~~~
def any(iterable):
for element in iterable:
if element:
return True
return False
~~~
2.5版本添加。
basestring()
這個抽象類型是[str](# "str")和[unicode](# "unicode")的超類。它不能被調用或者實例化,但是可以用來測試一個對象是否是[str](# "str")或者[unicode](# "unicode")的實例。isinstance(obj,basestring)等同于isinstance(obj,(str,unicode))。
出現于版本2.3。
bin(*x*)
將一個整數轉化成一個二進制字符串。結果是一個合法的Python表達式。如果*x*不是一個Python [int](# "int")對象,它必須定義一個返回整數的[__index__()](# "object.__index__")方法。
出現于版本2.6。
bool([*x*])
將一個值轉化成布爾值,使用標準的真值測試例程。如果*x*為假或者被忽略它返回[False](# "False");否則它返回[True](# "True")。[bool](# "bool")也是一個類,它是[int](# "int")的子類。[bool](# "bool")不能被繼承。它唯一的實例就是[False](# "False")和[True](# "True")。
出現于版本2.2.1。
改變于版本 2.3:如果沒有參數,函數返回[False](# "False")。
bytearray([*source*[, *encoding*[, *errors*]]])
返回一個新的字節數組。[bytearray](# "bytearray")類型是一個可變的整數序列,整數范圍為0 <= x < 256(即字節)。它有可變序列的大多數方法,參見[*Mutable Sequence Types*](#),同時它也有[str](# "str")類型的大多數方法,參見[*String Methods*](#)。
*source*參數可以以不同的方式來初始化數組,它是可選的:
- 如果是*string*,必須指明*encoding*(以及可選的*errors*)參數;[bytearray()](# "bytearray")使用[str.encode()](# "str.encode")將字符串轉化為字節數組。
- 如果是*integer*,生成相應大小的數組,元素初始化為空字節。
- 如果是遵循*buffer*接口的對象,對象的只讀buffer被用來初始化字節數組。
- 如果是*iterable*,它的元素必須是整數,其取值范圍為0<=x<256,用以初始化字節數組。
如果沒有參數,它創建一個大小為0的數組。
出現于版本2.6。
callable(*object*)
如果*object*參數可調用,返回[True](# "True");否則返回[False](# "False")。如果返回真,對其調用仍有可能失敗;但是如果返回假,對*object*的調用總是失敗。注意類是可調用的(對類調用返回一個新實例);如果類實例有[__call__()](# "object.__call__")方法,則它們也是可調用的。
chr(*i*)
返回一個單字符字符串,字符的ASCII碼為整數*i*。例如,chr(97)返回字符串'a'。它是[ord()](# "ord")的逆運算。參數的取值范圍為[0..255]的閉區間;如果*i*超出取值范圍,拋出[ValueError](# "exceptions.ValueError")。參見[unichr()](# "unichr")。
classmethod(*function*)
將*function*包裝成類方法。
類方法接受類作為隱式的第一個參數,就像實例方法接受實例作為隱式的第一個參數一樣。聲明一個類方法,使用這樣的慣例:
~~~
class C(object):
@classmethod
def f(cls, arg1, arg2, ...):
...
~~~
@classmethod是函數[*decorator*](#)(裝飾器)參見[*Function definitions*](#)中的函數定義。
它即可以通過類來調用(如C.f()),也可以通過實例來調用(如C().f())。除了實例的類,實例本身被忽略。如果在子類上調用類方法,子類對象被傳遞為隱式的第一個參數。
類方法不同于C++或Java中的靜態方法。如果你希望靜態方法,參見這節的[staticmethod()](# "staticmethod")。
需要類方法更多的信息,參見[*The standard type hierarchy*](#)中標準類型層次部分的文檔。
出現于版本2.2。
改變于版本2.4:添加了函數裝飾器語法。
cmp(*x*, *y*)
比較兩個對象*x*和*y*,根據結果返回一個整數。如果x<y,返回負數;如果x==y,返回0;如果x>y,返回正數。
compile(*source*, *filename*, *mode*[, *flags*[, *dont_inherit*]])
將*source*編譯成代碼對象,或者AST(Abstract Syntax Tree,抽象語法樹)對象。代碼對象可以經由[exec](#)語句執行,或者通過調用[eval()](# "eval")演算。*source*可以是Unicode字符串,*Latin-1*編碼的字符串或者AST對象。參考[ast](# "ast: Abstract Syntax Tree classes and manipulation.")模塊文檔以了解如何和AST對象一起使用的信息。
*filename*參數指明一個文件,從該文件中讀取(源)代碼;如果代碼不是從文件中讀入,傳遞一個可識別的值(一般用'<string>')。
*mode*參數指明了編譯成哪一類的代碼;它可以是'exec',如果*source*包含一組語句;也可以是'eval',如果是單一的表達式;或者是'single',如果是單一的交互式語句(對于最后一種情況,如果表達式語句演算成非None,它的值會被打印)。
可選的參數*flags*和*dont_inherit*控制哪些future語句(見[**PEP 236**](http://www.python.org/dev/peps/pep-0236))影響*source*的編譯。如果沒有這兩個參數(或者都為0),使用調用compile的代碼當前有效的future語句來編譯source。如果給出了*flags*參數且沒有給出*dont_inherit*參數(或者為0),除了本該使用的future語句之外,由*flags*參數指明的future語句也會影響編譯。如果*dont_inherit*是非0整數,*flags*參數被忽略(調用compile周圍的有效的future語句被忽略)。
future語句由bit位指明,這些bit可以做或運算,以指明多個語句。可以在[__future__](# "__future__: Future statement definitions")模塊中,_Feature實例的compiler_flag屬性找到指明功能的bit位。
如果被編譯的源代碼是不合法的,函數拋出[SyntaxError](# "exceptions.SyntaxError");如果源代碼包含空字節,函數拋出[TypeError](# "exceptions.TypeError")。
注意
當以'single'或者'eval'模式編譯多行代碼字符串的時候,輸入至少以一個新行結尾。這主要是便于[code](# "code: Facilities to implement read-eval-print loops.")模塊檢測語句是否結束。
改變于版本 2.3:添加了*flags*和*dont_inherit*參數。
改變于版本2.6:支持編譯AST對象。
改變于版本2.7:允許使用Windows和Mac的新行字符。'exec'模式下的輸入不需要以新行結束。
complex([*real*[, *imag*]])
創建一個復數,它的值為*real* + *imag**j;或者將一個字符串/數字轉化成一個復數。如果第一個參數是個字符串,它將被解釋成復數,同時函數不能有第二個參數。第二個參數不能是字符串。每個參數必須是數值類型(包括復數)。如果*imag*被忽略,它的默認值是0,這時該函數就像是[int()](# "int"),[long()](# "long")和[float()](# "float")這樣的數值轉換函數。如果兩個參數都被忽略,返回0j。
注意
當從字符串轉化成復數的時候,字符串中+或者-兩邊不能有空白。例如,complex('1+2j')是可行的,但complex('1+2j')會拋出[ValueError](# "exceptions.ValueError")異常。
在[*Numeric Types — int, float, long, complex*](#)中有對復數的描述。
delattr(*object*, *name*)
這個函數和[setattr()](# "setattr")有關。參數是一個對象和一個字符串。字符串必須是對象的某個屬性的名字。只要對象允許,這個函數刪除該名字對應的屬性。例如,delattr(x,'foobar')等同于delx.foobar。
dict(***kwarg*)dict(*mapping*, ***kwarg*)dict(*iterable*, ***kwarg*)
創建一個新字典。[dict](# "dict")對象就是字典類。參見[dict](# "dict")和[*Mapping Types — dict*](#)以得到關于該類的文檔。
參見[list](# "list"),[set](# "set"),和[tuple](# "tuple")類以及[collections](# "collections: High-performance datatypes")模塊了解其它的容器。
dir([*object*])
如果沒有參數,返回當前本地作用域內的名字列表。如果有參數,嘗試返回參數所指明對象的合法屬性的列表。
如果對象有__dir__()方法,該方法被調用且必須返回一個屬性列表。這允許實現了定制化的[__getattr__()](# "object.__getattr__")或者[__getattribute__()](# "object.__getattribute__")函數的對象定制[dir()](# "dir")報告對象屬性的方式。
如果對象沒有提供__dir__(),同時如果對象有定義__dict__屬性,dir()會先嘗試從__dict__屬性中收集信息,然后是對象的類型對象。結果列表沒有必要是完整的,如果對象有定制化的[__getattr__()](# "object.__getattr__"),結果還有可能是不準確的。
對于不同類型的對象,默認的[dir()](# "dir")行為也不同,因為它嘗試產生相關的而不是完整的信息:
- 如果對象是模塊對象,列表包含模塊的屬性名。
- 如果對象是類型或者類對象,列表包含類的屬性名,及它的基類的屬性名。
- 否則,列表包含對象的屬性名,它的類的屬性名和類的基類的屬性名。
返回的列表按字母順序排序。例如:
~~~
>>> import struct
>>> dir() # show the names in the module namespace
['__builtins__', '__doc__', '__name__', 'struct']
>>> dir(struct) # show the names in the struct module
['Struct', '__builtins__', '__doc__', '__file__', '__name__',
'__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
'unpack', 'unpack_from']
>>> class Shape(object):
def __dir__(self):
return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'perimeter', 'location']
~~~
注意
因為[dir()](# "dir")主要是為了在交互式環境下使用方便,它嘗試提供有意義的名字的集合,而不是提供嚴格或一致定義的名字的集合,且在不同的版本中,具體的行為也有所變化。例如,如果參數是一個類,那么元類屬性就不會出現在結果中。
divmod(*a*, *b*)
在長整數除法中,傳入兩個數字(非復數)作為參數,返回商和余數的二元組。對于混合的操作數類型,應用二元算術運算符的規則。對于一般或者長整數,結果等同于(a//b,a%b)。對于浮點數結果是(q,a%b),*q*一般是math.floor(a/b),但也可能比那小1。不管怎樣,q*b+a%b非常接近于*a*,如果a%b非0,它和*b*符號相同且0<=abs(a%b)<abs(b)。
改變于版本2.3:廢棄了在[divmod()](# "divmod")中使用復數。
enumerate(*sequence*, *start=0*)
返回一個枚舉對象。*sequence*必須是個序列,迭代器[*iterator*](#),或者支持迭代的對象。[enumerate()](# "enumerate")返回的迭代器的next()方法返回一個元組,它包含一個計數(從*start*開始,默認為0)和從*sequence*中迭代得到的值:
~~~
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
~~~
等同于:
~~~
def enumerate(sequence, start=0):
n = start
for elem in sequence:
yield n, elem
n += 1
~~~
出現于版本2.3。
改變于版本2.6:添加了*start*參數。
eval(*expression*[, *globals*[, *locals*]])
參數是Unicode或者*Latin-1*編碼的字符串,全局變量和局部變量可選。如果有全局變量,*globals*必須是個字典。如果有局部變量,*locals*可以是任何映射類型對象。
改變于版本2.4:在此之前*locals*需要是個字典。
*expression*參數被當作Python表達式來解析并演算(技術上來說,是個條件列表),使用*globals*和*locals*字典作為全局和局部的命名空間。如果*globals*字典存在,且缺少‘__builtins__’,在*expression*被解析之前,當前的全局變量被拷貝進*globals*。這意味著一般來說*expression*能完全訪問標準[__builtin__](# "__builtin__: The module that provides the built-in namespace.")模塊,且受限的環境會傳播。如果*locals*字典被忽略,默認是*globals*字典。如果都被忽略,表達式在[eval()](# "eval")被調用的環境中執行。返回值是被演算的表達式的結果。語法錯誤報告成異常。例子:
~~~
>>> x = 1
>>> print eval('x+1')
2
~~~
該函數也能執行任意的代碼對象(如[compile()](# "compile")返回的結果)。在這種情況下,傳遞代碼對象而不是字符串。如果代碼對象編譯時*mode*參數為'exec',[eval()](# "eval")返回None。
提示:[exec](#)語句支持動態的語句執行。[execfile()](# "execfile")函數支持執行文件中的語句。[globals()](# "globals")和[locals()](# "locals")函數返回當前的全局變量和局部變量的字典,可以傳遞給[eval()](# "eval")或者[execfile()](# "execfile")。
參見[ast.literal_eval()](# "ast.literal_eval"),該函數能安全演算只含字面量的表達式的字符串。
execfile(*filename*[, *globals*[, *locals*]])
該函數類似于[exec](#)語句,它解析一個文件而不是字符串。它不同于[import](#)語句的地方在于它不使用模塊管理——它無條件的讀入文件且不會創建一個新模塊。[[1]](#)
參數是個文件名和兩個可選的字典。文件被當成Python語句序列來解析并演算(類似于模塊),使用*globals*和*locals*字典作為全局和局部的命名空間。如果存在,*locals*可以是任意的映射類型對象。記住在模塊級別,全局和局部字典是同一個字典。如果*globals*和*locals*是兩個不同的對象,代碼就好象是嵌入在類定義中被執行。
改變于版本2.4:在此之前*locals*必須是個字典。
如果*locals*字典被忽略,默認是*globals*字典。如果兩個字典都被忽略,表達式在[execfile()](# "execfile")被調用的環境中執行。返回None。
注意
默認的*locals*的行為和下述的[locals()](# "locals")函數一樣:不應該嘗試修改默認的*locals*字典。如果在[execfile()](# "execfile")函數返回后,你希望看到作用于*locals*的代碼的效果,顯示地傳遞一個*locals*字典。[execfile()](# "execfile")不能用于可靠地修改一個函數的局部變量。
file(*name*[, *mode*[, *buffering*]])
[file](# "file")類型的構造函數,進一步的描述見[*File Objects*](#)章節。構造函數的參數同下述的[open()](# "open")內置函數。
要打開一個文件,建議使用[open()](# "open")而不是直接調用該構造函數。[file](# "file")更適合于類型測試(例如,isinstance(f,file))。
出現于版本2.2。
filter(*function*, *iterable*)
構造一個列表,列表的元素來自于*iterable*,對于這些元素*function*返回真。*iterable*可以是個序列,支持迭代的容器,或者一個迭代器。如果*iterable*是個字符串或者元組,則結果也是字符串或者元組;否則結果總是列表。如果*function*是None,使用特性函數,即為假的*iterable*被移除。
注意,在function不為None的情況下,filter(function,iterable)等同于[itemforiteminiterableiffunction(item)];否則等同于[itemforiteminiterableifitem](function為None)。
參見[itertools.ifilter()](# "itertools.ifilter")和[itertools.ifilterfalse()](# "itertools.ifilterfalse"),以得到該函數的迭代器版本,以及該函數的變體(過濾*function*返回假的元素)。
float([*x*])
將字符串或者數字轉化成浮點數。如果參數是字符串,它必須包含小數或者浮點數(可以有符號),周圍可以有空白。參數也可以是[+|-]nan或者[+|-]inf。其它情況下,參數可以是原始/長整數或者浮點數,(以Python的浮點數精度)返回具有相同值的浮點數。如果沒有參數,返回0.0。
注意
當傳遞字符串時,依賴于底層的C庫,可以返回NaN(Not a Number,不是一個數字)和Infinity(無窮大)這樣的值。該函數接受字符串nan(NaN),inf(正無窮大)和-inf(負無窮大)。對于NaN,不區分大小寫和+/-號。總是用nan,inf或者-inf來表示NaN和Infinity。
float類型描述于[*Numeric Types — int, float, long, complex*](#)。
format(*value*[, *format_spec*])
將*value*轉化成“格式化”的表現形式,格式由*format_spec*控制。對*format_spec*的解釋依賴于*value*參數的類型,大多數內置類型有標準的格式化語法:[*Format Specification Mini-Language*](#)。
注意
format(value,format_spec)僅僅調用value.__format__(format_spec)。
出現于版本2.6。
frozenset([*iterable*])
返回一個新的[frozenset](# "frozenset")對象,如果可選參數*iterable*存在,frozenset的元素來自于iterable。frozenset是個內置類。參見[frozenset](# "frozenset")和[*Set Types — set, frozenset*](#)。
關于其它容器,參見[set](# "set"),[list](# "list"),[tuple](# "tuple"),和[dict](# "dict")類,以及[collections](# "collections: High-performance datatypes")模塊。
出現于版本2.4。
getattr(*object*, *name*[, *default*])
返回*object*的屬性值。*name*必須時個字符串。如果字符串時對象某個屬性的名字,則返回該屬性的值。例如,getattr(x,'foobar')等同于x.foobar。如果名字指明的屬性不存在,且有*default*參數,default被返回;否則拋出[AttributeError](# "exceptions.AttributeError")。
globals()
返回表示當前全局符號表的字典。它總是當前模塊的字典(在函數或者方法中,它指定義的模塊而不是調用的模塊)。
hasattr(*object*, *name*)
參數是一個對象和一個字符串。如果字符串是對象某個屬性的名字,返回True;否則返回False。(實現方式為調用getattr(object,name),看它是否拋出異常)。
hash(*object*)
返回對象的hash(哈希/散列)值(如果有的話)。hash值是整數。它被用于在字典查找時快速比較字典的鍵。相同的數值有相同的hash(盡管它們有不同的類型,比如1和1.0)。
help([*object*])
調用內置的幫助系統。(這個函數主要用于交互式使用。)如果沒有參數,在解釋器的控制臺啟動交互式幫助系統。如果參數是個字符串,該字符串被當作模塊名,函數名,類名,方法名,關鍵字或者文檔主題而被查詢,在控制臺上打印幫助頁面。如果參數是其它某種對象,生成關于對象的幫助頁面。
這個函數經由[site](# "site: Module responsible for site-specific configuration.")模塊加入內置的命名空間。
出現于版本2.2。
hex(*x*)
將任意大小的整數轉化成以“0x”打頭的小寫的十六進制字符串,例如:
~~~
>>> hex(255)
'0xff'
>>> hex(-42)
'-0x2a'
>>> hex(1L)
'0x1L'
~~~
如果x不是Python的[int](# "int")或者[long](# "long")對象,它必須定義__index__()方法以返回一個整數。
參見[int()](# "int"),它將十六進制字符串轉化成一個整數。
注意
使用[float.hex()](# "float.hex")方法得到浮點數的十六進制字符串表示。
改變于版本2.4:在此之前只返回無符號數。
id(*object*)
返回對象的“標識”。這是一個整數(或長整數),保證在對象的生命期內唯一且不變。生命期不重疊的兩個對象可以有相同的[id()](# "id")值。
**CPython實現細節:**這是對象的內存地址。
input([*prompt*])
等同于eval(raw_input(prompt))。
該函數不會捕獲用戶錯誤。如果輸入語法不合法,將拋出[SyntaxError](# "exceptions.SyntaxError")。如果演算中有錯誤,將拋出其它異常。
如果有裝載[readline](# "readline: GNU readline support for Python. (Unix)"),[input()](# "input")將會用它來提供復雜的行編輯和歷史功能。
考慮使用[raw_input()](# "raw_input")函數來得到用戶的一般輸入。
int(*x=0*)int(*x*, *base=10*)
將數字或字符串*x*轉化成一個整數,如果沒有參數則返回0。如果*x*是個數字,它可以是原始/長整數,或者浮點數。如果*x*是浮點數,則向0截斷。如果參數超出了整數的范圍,則返回長整數對象。
如果*x*不是個數字,或者存在*base*參數,則*x*必須是個表示以*base*為基數的[*integer literal*](#)(整數字面量)的字符串或者Unicode對象。字面量的前面可以有+或者-(中間不能有空格),周圍可以有空白。以n為基數的字面量包含數字0到n-1,用a到z(或者A到Z)來表示10到35。默認的*base*是10。允許的值為0和2-36。二進制,八進制和十六進制的字面量前面可以有0b/0B,0o/0O/0,或者0x/0X,就像代碼中的整數字面量一樣。基數0表示嚴格按整數字面量來解釋字符串,所以實際的基數為2,8,10或者16。
整數類型描述于[*Numeric Types — int, float, long, complex*](#)。
isinstance(*object*, *classinfo*)
如果參數*object*是參數*classinfo*的一個實例;或者是一個子類(直接的,間接的,或者[*virtual*](#)),返回真。如果*classinfo*是類型對象(新式類)而*object*是該類型對象;或者是其子類(直接的,間接的,或者[*virtual*](#)),返回真。如果*object*不是給定類型的類實例或者對象,該函數總是返回假。如果*classinfo*既不是類對象,也不是類型對象,它可以是類/類型對象的元組,或者遞歸包含這樣的元組(不接受其它的序列類型)。如果*classinfo*不是類,類型,類/類型的元組,拋出[TypeError](# "exceptions.TypeError")異常。
改變于版本2.2:添加對類型信息的元組的支持。
issubclass(*class*, *classinfo*)
如果*class*是*classinfo*的子類(直接的,間接的,或者[*virtual*](#)) ,返回真。一個類被認為是它自己的子類。*classinfo*可以是類對象的元組,這時*classinfo*中的每個類對象都會被檢查。其它情況下,拋出[TypeError](# "exceptions.TypeError")異常。
改變于版本2.3:添加對類型信息的元組的支持。
iter(*o*[, *sentinel*])
返回一個[*iterator*](#)對象。根據有無第二個參數,對第一個參數的解釋相差很大。如果沒有第二個參數,*o*必須是個集合對象,要么支持迭代協議(即 [__iter__()](# "object.__iter__")方法),要么支持序列協議(即[__getitem__()](# "object.__getitem__")方法,整數參數從0開始)。如果這些協議都不支持,拋出[TypeError](# "exceptions.TypeError")。如果有第二個參數*sentinel*,*o*必須是個可調用對象。這種情況下返回的迭代,每當調用其[next()](# "iterator.next")方法時,將會調用*o*(不帶參數);如果返回值等于*sentinel*,拋出[StopIteration](# "exceptions.StopIteration"),否則返回該值。
第二種形式的[iter()](# "iter")的一個有用的應用就是讀一個文件的行,直到讀到特定行。下面的例子讀一個文件,直到[readline()](# "io.TextIOBase.readline")方法返回一個空字符串:
~~~
with open('mydata.txt') as fp:
for line in iter(fp.readline, ''):
process_line(line)
~~~
出現于版本2.2。
len(*s*)
返回對象的長度(元素的個數)。參數可以是序列(如字符串,字節,元組,列表或者范圍)或者集合(如字典,集合或者固定集合)。
list([*iterable*])
返回一個列表,其元素來自于*iterable*(保持相同的值和順序)。*iterable*可以是個序列,支持迭代的容器,或者迭代器對象。如果*iterable*已經是個列表,返回其拷貝,類似于iterable[:]。例如,list('abc')返回['a','b','c'],list((1,2,3))返回[1,2,3]。如果沒有參數,返回一個新的空的列表,[]。
[list](# "list")是可變序列類型,見文檔[*Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange*](#)。關于其它容器參見內置[dict](# "dict"),[set](# "set"),和[tuple](# "tuple")類,以及[collections](# "collections: High-performance datatypes")模塊。
locals()
更新并返回表示當前局部符號表的字典。當locals在函數塊中而不是類塊中被調用時,[locals()](# "locals")返回自由變量。
注意
不應該修改該字典的內容;所做的改變不一定會影響到解釋器所用的局部和自由變量的值。
long(*x=0*)long(*x*, *base=10*)
將一個字符串或者數字轉化成一個長整數。如果參數時個字符串,它必須包含一個數字,任意大小,可以有符號,周圍可以有空白。*base*參數和[int()](# "int")中的一樣,只有當*x*是字符串的時候才能有此參數。其它情況下,參數可以是個原始/長整數,或者浮點數,返回具有相同值的長整數。浮點數轉成整數時將浮點數向零截斷。如果沒有參數,返回0L。
長整數類型描述于[*Numeric Types — int, float, long, complex*](#)。
map(*function*, *iterable*, *...*)
將*function*應用于*iterable*的每一個元素,返回結果的列表。如果有額外的*iterable*參數,并行的從這些參數中取元素,并調用*function*。如果一個參數比另外的要短,將以None擴展該參數元素。如果*function*是None使用特性函數;如果有多個參數,[map()](# "map")返回一元組列表,元組包含從各個參數中取得的對應的元素(某種變換操作)。*iterable*參數可以是序列或者任意可迭代對象;結果總是列表。
max(*iterable*[, *key*])max(*arg1*, *arg2*, **args*[, *key*])
返回可迭代的對象中的最大的元素,或者返回2個或多個參數中的最大的參數。
如果有一個位置參數,*iterable*必須是個非空的可迭代對象(如非空字符串,元組或者列表)。返回可迭代對象中最大的元素。如果有2個或更多的位置參數,返回最大位置參數。
可選的*key*參數指明了有一個參數的排序函數,如list.sort()中使用的排序函數。如果有*key*參數,它必須是關鍵字參數(例如,max(a,b,c,key=func))。
改變于版本2.5:添加了對可選參數*key*的支持。
memoryview(*obj*)
返回給定參數的“內存視圖”。參見[*memoryview type*](#)。
min(*iterable*[, *key*])min(*arg1*, *arg2*, **args*[, *key*])
返回可迭代的對象中的最小的元素,或者返回2個或多個參數中的最小的參數。
如果有一個位置參數,*iterable*必須是個非空的可迭代對象(如非空字符串,元組或者列表)。返回可迭代對象中最小的元素。如果有2個或更多的位置參數,返回最小的位置參數。
可選的*key*參數指明了有一個參數的排序函數,如list.sort()中使用的排序函數。如果有*key*參數,它必須是關鍵字參數(例如,min(a,b,c,key=func))。
改變于版本2.5:添加了對可選參數*key*的支持。
next(*iterator*[, *default*])
通過調用*iterator*的[next()](# "iterator.next")方法,得到它的下一個元素。如果有*default*參數,在迭代器迭代完所有元素之后返回該參數;否則拋出[StopIteration](# "exceptions.StopIteration")。
出現于版本2.6。
object()
返回一個新的無特征的對象。[object](# "object")是所有新式類的基類。它有對所有新式類的實例通用的方法。
出現于版本2.2。
改變于版本2.3:改函數不接受任何的參數。在以前,它接受參數,但是會被忽略掉。
oct(*x*)
將一個(任意尺寸)整數轉化成一個八進制字符串。結果是一個合法的Python表達式。
改變于版本2.4:以前只返回一個無符號數字面量。
open(*name*[, *mode*[, *buffering*]])
打開一個文件,返回一個[file](# "file")類型的對象,file類型描述于[*File Objects*](#)章節。如果文件不能打開,拋出[IOError](# "exceptions.IOError")。當要打開一個文件,優先使用[open()](# "open"),而不是直接調用[file](# "file")構造函數。
頭兩個參數類似于stdio‘s fopen()的參數:*name*是要打開的文件的名字,*mode*是個指示如何打開文件的字符串。
*mode*的常用值包括:'r'讀文件;'w'寫文件(如果文件存在則截斷之);'a' 附加(在 *某些*Unix系統上意味著*所有*的寫操作附加到文件的末尾,不管當前的寫位置)。如果沒有*mode*,默認是'r'。默認使用文本模式,它會在寫文件時將'\n'字符轉化成平臺特定的字符,在讀文件時又轉回來。因此在打開二進制文件的時候,要以二進制模式打開文件,把'b'添加到*mode*值,這樣可以增強可移植性。(在不區分二進制文件和文本文件的系統上,附加'b'仍然時有用的,它可以起到文檔的目的。)參見下文以得到*mode*更多的可能的值。
可選的*buffering*參數指明了文件需要的緩沖大小:0意味著無緩沖;1意味著行緩沖;其它正值表示使用參數大小的緩沖(大概值,以字節為單位)。負的*buffering*意味著使用系統的默認值,一般來說,對于tty設備,它是行緩沖;對于其它文件,它是全緩沖。如果沒有改參數,使用系統的默認值。[[2]](#)
模式'r+','w+'和'a+'打開文件以便更新(同時讀寫)。注意'w+'會截斷文件。在區分文本文件和二進制文件的系統上,在模式中附加'b'會以二進制模式打開文件;在不區分的系統上,添加'b'沒有效果。
除了標準的fopen()模式值,*mode*可以是'U'或者'rU'。構建Python時一般會添加[*universal newlines*](#)(統一新行)支持;'U'會以文本模式打開文件,但是行可以以以下字符結束:'\n'(Unix行結束符),'\r'(Macintosh慣例),或者'\r\n'(Windows慣例)。Python程序會認為它們都是'\n'。如果構建Python時沒有添加統一新行的支持,*mode*'U'和普通文本模式一樣。注意,這樣打開的文件對象有一個叫newlines的屬性,它的值是None(沒有發現新行),'\n','\r','\r\n',或者是包含所有已發現的新行字符的元組。
Python要求模式字符串在去除'U'后以'r','w'或者'a'開頭。
Python提供了許多文件處理模塊,包括[fileinput](# "fileinput: Loop over standard input or a list of files."),[os](# "os: Miscellaneous operating system interfaces."),[os.path](# "os.path: Operations on pathnames."),[tempfile](# "tempfile: Generate temporary files and directories.")和[shutil](# "shutil: High-level file operations, including copying.")。
改變于版本2.5:引入了對模式字符串第一個字符的限制。
ord(*c*)
給定一個長度為一的字符串,如果參數是unicode對象,則返回表示字符的代碼點的整數;如果參數是八位字符串,返回字節值。例如,ord('a')返回整數97,ord(u'\u2020')返回8224。它是八位字符串[chr()](# "chr")的反函數,也是unicode對象[unichr()](# "unichr")的反函數。如果參數是unicode且構建Python時添加了UCS2 Unicode支持,那么字符的碼點必須在[0..65535]的閉區間;如果字符串的長度為2,則拋出[TypeError](# "exceptions.TypeError")。
pow(*x*, *y*[, *z*])
返回*x* 的 *y*次冪;如果 *z* 提供的時候,, 返回 *x* 的 *y* 次冪,然后對 ?*z* 取模。(這樣比 pow(x,y)%z) 更高效。兩個參數的形式 pow(x,y) 與使用 操作符: x**y 是等價的。
參數必須是數字類型的。由于操作數是混合類型的,二進制計算的原因需要一些強制的規定。對于整型和長整型的操作數,計算結果和操作數(強制后的)是相同的類型。除非第二個 參數是負數。在這種情況下, 所有的參數都會被轉化成浮點型,并且會返回一個浮點的結果。例如, 10**2 返回 100, 但 10**-2 返回0.01.(這個新特性被加入在Python2.2中在Python2.1和之前的版本中,如果兩個參數是整型,并且第二個參數為負數的情況下,會拋出一個異常。)如果第二個參數為負數,那么第三個參數必須省略。如果提供參數 *z* , *x* and *y* 必須為整數,而且*y*要是非負整數。(這個限制是在Python2.2加入的。Python2.1以及之前的版本, 三個參數都是浮點型的pow() 版本,返回的結果依賴 平臺 對于浮點數的取整情況。)
print(**objects*, *sep=' '*, *end='\n'*, *file=sys.stdout*)
以sep分割,end的值結尾,將 目標對象 打印到 文件流中。*sep*, *end* 和 *file*,如果提供這三個參數的話,必須以鍵值的形式。
所有非鍵值形式提供的參數,都被轉化為字符串,就像用str()轉化那樣。[](# "str")然后寫到 文件流中,以 *sep* 分割, *end* 結尾。*sep* and *end* 都必須是字符串形式的;也可以留成 None, 這樣會使用默認值。如果沒有打印 *對象*, [print()](# "print") 只打印一個 結束符號 *end*.
*file* 參數一定要是含有 write(string)方法的對象 ;如果該參數為空,或為None, 默認使用[sys.stdout](# "sys.stdout")?作為輸出。輸出緩沖方式由*file*決定。例如 ,使用file.flush() 來確保, 立即顯示在屏幕上.
Note
This function is not normally available as a built-in since the name print is recognized as the [print](#) statement.為了使得print語句失效,而使用 [print()](# "print") 函數, 可以使用future 語句 在你的模塊上面:
~~~
from __future__ import print_function
~~~
2.6 版中新增。
property([*fget*[, *fset*[, *fdel*[, *doc*]]]])
返回[*新式類*](#)(繼承自[object](# "object")的類)的一個屬性。
*fget*是用于獲取屬性值的函數,類似地*fset*用于設置屬性,*fdel*用于刪除屬性。典型的用法是定義一個托管的屬性:x:
~~~
class C(object):
def __init__(self):
self._x = None
def getx(self):
return self._x
def setx(self, value):
self._x = value
def delx(self):
del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")
~~~
假設*c*是*C*的一個實例,c.x將調用獲取函數,c.x=value調用設置函數,delc.x調用刪除函數。
如果給出*doc*,它將是該屬性的文檔字符串。否則,該屬性將拷貝*fget*的文檔字符串(如果存在)。這使得用[property()](# "property")作為[*裝飾器*](#)創建一個只讀屬性非常容易:
~~~
class Parrot(object):
def __init__(self):
self._voltage = 100000
@property
def voltage(self):
"""Get the current voltage."""
return self._voltage
~~~
將voltage()方法轉換為一個與只讀屬性具有相同名稱的獲取函數。
A property object has getter, setter, and deleter methods usable as decorators that create a copy of the property with the corresponding accessor function set to the decorated function.最好的解釋就是使用一個例子:
~~~
class C(object):
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
~~~
這段代碼與第一個例子完全相等。請確保給額外的函數與原始的屬性相同的名字(此例中為x。)
The returned property also has the attributes fget, fset, and fdel corresponding to the constructor arguments.
2.2版中新增。
2.5版中的變化:如果*doc*沒有給出則使用*fget*的文檔字符串。
2.6版中的變化:添加getter、setter和deleter屬性。
range(*stop*)range(*start*, *stop*[, *step*])
這是一個創建算術級數列表的通用函數。它最常用于[for](#)循環。參數必須為普通的整數。如果*step*參數省略,則默認為1。如果*start*參數省略,則默認為0。該函數的完整形式返回一個整數列表[start,start+step,start+2*step,...]。如果*step*為正,則最后一個元素start+i*step最大且小于*stop*;如果*step*為負,則最后一個元素start+i*step最小且大于*stop*。*step*必須不能為零(否則會引發[ValueError](# "exceptions.ValueError"))。示例:
~~~
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5)
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(0, -10, -1)
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]
~~~
raw_input([*prompt*])
如果有*prompt*參數,則將它輸出到標準輸出且不帶換行。該函數然后從標準輸入讀取一行,將它轉換成一個字符串(去掉一個末尾的換行符),然后返回它。當讀到EOF時,則引發[EOFError](# "exceptions.EOFError")。示例:
~~~
>>> s = raw_input('--> ')
--> Monty Python's Flying Circus
>>> s
"Monty Python's Flying Circus"
~~~
如果已經加載[readline](# "readline: GNU readline support for Python. (Unix)")模塊,那么[raw_input()](# "raw_input")將用它來提供優雅的行編輯和歷史功能。
reduce(*function*, *iterable*[, *initializer*])
將帶有兩個參數的*function*累計地應用到*iterable*的元素上,從左向右,以致將可迭代序列reduce為一個單一的值。例如,reduce(lambdax,y:x+y,[1,2,3,4,5])相當于計算((((1+2)+3)+4)+5)。左邊的參數*x*是累計之后的值,右邊的參數*y*是來自*iterable*中的修改值。如果提供可選的參數*initializer*,它在計算時放在可迭代序列的最前面,并且當可迭代序列為空時作為默認值。如果*initializer*沒有給出,且*iterable*只包含一個元素,將返回第一個元素。大致等同于:
~~~
def reduce(function, iterable, initializer=None):
it = iter(iterable)
if initializer is None:
try:
initializer = next(it)
except StopIteration:
raise TypeError('reduce() of empty sequence with no initial value')
accum_value = initializer
for x in it:
accum_value = function(accum_value, x)
return accum_value
~~~
reload(*module*)
重載之前已經引入過的*模塊*.參數必須是一個模型對象,所以之前它必須成功導入。如果你用外部編輯器編輯了模型的源文件并且打算在不離開python解釋器的情況下使用模型的新版本,reload將非常有用。返回值是該模塊對象(與*module*參數相同)。
當執行reload(module)時:
- python模型的代碼將重新編譯并且模型級的代碼會重新執行,定義一系列對象,這些對象的名字和模型字典中的名字相關聯。改進后的模型的 init 函數不會第二次加載。
- 跟Python其他對象一樣,舊的對象只有在他們的引用計數將為0的時候被系統收回。
- 模型命名空間中的名字自動升級指向新的或者修改后的對象。
- 對舊對象的其他引用(比如模型延展的命名)不會連接到新的改進對象。每一個命名空間在被請求的時候,都必須更新。
這里有一些列的其他警告:
If a module is syntactically correct but its initialization fails, the first [import](#) statement for it does not bind its name locally, but does store a (partially initialized) module object in sys.modules.To reload the module you must first [import](#) it again (this will bind the name to the partially initialized module object) before you can [reload()](# "reload") it.
When a module is reloaded, its dictionary (containing the module’s global variables) is retained.Redefinitions of names will override the old definitions, so this is generally not a problem.If the new version of a module does not define a name that was defined by the old version, the old definition remains.This feature can be used to the module’s advantage if it maintains a global table or cache of objects — with a [try](#) statement it can test for the table’s presence and skip its initialization if desired:
~~~
try:
cache
except NameError:
cache = {}
~~~
It is legal though generally not very useful to reload built-in or dynamically loaded modules, except for [sys](# "sys: Access system-specific parameters and functions."), [__main__](# "__main__: The environment where the top-level script is run.") and [__builtin__](# "__builtin__: The module that provides the built-in namespace.").In many cases, however, extension modules are not designed to be initialized more than once, and may fail in arbitrary ways when reloaded.
If a module imports objects from another module using [from](#) ...[import](#) ..., calling [reload()](# "reload") for the other module does not redefine the objects imported from it — one way around this is to re-execute the [from](#) statement, another is to use [import](#) and qualified names (*module*.*name*) instead.
If a module instantiates instances of a class, reloading the module that defines the class does not affect the method definitions of the instances — they continue to use the old class definition.The same is true for derived classes.
repr(*object*)
返回某個對象可打印形式的字符串。它與字符串轉換式(反引號)產生的值相同。有時候能夠把這個操作作為一個普通的函數訪問非常有用。For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to [eval()](# "eval"), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object.類可以通過定義[__repr__()](# "object.__repr__")方法控制該函數對其實例的返回。
reversed(*seq*)
返回一個反轉的[*迭代器*](#)。*seq*必須是一個具有[__reversed__()](# "object.__reversed__") 方法或支持序列協議的對象(整數參數從0開始的[__len__()](# "object.__len__")方法和[__getitem__()](# "object.__getitem__") 方法)。
2.4版中新增。
2.6版中的變化:添加可以編寫一個定制的[__reversed__()](# "object.__reversed__")方法的可能。
round(*number*[, *ndigits*])
返回一個浮點型 *近似值*,保留小數點后 *ndigits* 位。如果省略*ndigits*,它默認為零。結果是一個浮點數。Values are rounded to the closest multiple of 10 to the power minus *ndigits*;if two multiples are equally close, rounding is done away from 0 (所以,例如,round(0.5)是1.0 且round(-0.5)是-1.0)。
Note
浮點數[round()](# "round")的行為可能讓人驚訝,例如round(2.675,2)給出的是2.67 而不是期望的2.68。這不是一個錯誤:大部分十進制小數不能用浮點數精確表示,它是因為這樣的一個事實的結果。更多信息,請參閱[*Floating Point Arithmetic: Issues and Limitations*](#)。
set([*iterable*])
返回一個新的[set](# "set") 對象,其元素可以從可選的*iterable*獲得。set是一個內建的類。關于該類的文檔,請參閱[set](# "set")和[*集合類型 — set, frozenset*](#)。
關于其它容器請參閱內建的[frozenset](# "frozenset")、[list](# "list")、[tuple](# "tuple")和[dict](# "dict")類,還有[collections](# "collections: High-performance datatypes")模塊。
2.4版中新增。
setattr(*object*, *name*, *value*)
[getattr()](# "getattr")的相反操作。參數是一個對象、一個字符串和任何一個值。字符串可以是一個已存在屬性的名字也可以是一個新屬性的名字。該函數將值賦值給屬性,只要對象允許。例如,setattr(x,'foobar',123)等同于x.foobar=123。
slice(*stop*)slice(*start*, *stop*[, *step*])
返回一個[*slice*](#)對象,表示由索引range(start,stop,step)指出的集合。*start*和*step*參數默認為None。切片對象具有只讀屬性start、stop和step,它們僅僅返回參數的值(或者它們的默認值)。它們沒有其他顯式的函數;它是它們用于Numerical Python和其它第三方擴展。在使用擴展的索引語法時同樣會生成切片對象。例如:a[start:stop:step]或a[start:stop,i]。返回迭代器的另外一個版本可以參閱[itertools.islice()](# "itertools.islice")。
sorted(*iterable*[, *cmp*[, *key*[, *reverse*]]])
依據*iterable*中的元素返回一個新的列表。
可選參數*cmp*、*key*和*reverse*與list.sort()方法的參數含義相同(在[*可變的序列類型*](#)一節描述)。
*cmp*指定一個定制化的帶有兩個參數的比較函數(可迭代的元素),它應該根據第一個參數是小于、等于還是大于第二個參數返回負數、零或者正數:cmp=lambdax,y:cmp(x.lower(),y.lower())。默認值是None。
*key*指定一個帶有一個參數的函數,它用于從每個列表元素選擇一個比較的關鍵字:key=str.lower。默認值是None(直接比較元素)。
*reverse*是一個布爾值。如果設置為True,那么列表元素以反向比較排序。
通常情況下,*key*和*reverse*轉換處理比指定一個等同的*cmp*函數要快得多。這是因為*cmp*為每個元素調用多次但是*key*和*reverse*只會觸摸每個元素一次。使用[functools.cmp_to_key()](# "functools.cmp_to_key")來轉換舊式的*cmp*函數為*key*函數。
關于排序的實例和排序的簡明教程,請參閱[Sorting HowTo](http://wiki.python.org/moin/HowTo/Sorting/)。
2.4版中新增。
staticmethod(*function*)
返回*function*的一個靜態方法。
靜態方法不接受隱式的第一個參數。要聲明靜態方法,請使用下面的習慣方式:
~~~
class C(object):
@staticmethod
def f(arg1, arg2, ...):
...
~~~
@staticmethod形式是一個函數[*裝飾器*](#) – 細節請參閱[*函數定義*](#)中函數定義的描述。
它既可以在類上調用(例如C.f())也可以在實例上調用(例如C().f())。除了它的類型,實例其他的內容都被忽略。
Python中的靜態方法類似于Java或C++。關于創建類構造器的另外一種方法,請參閱[classmethod()](# "classmethod")。
更多關于靜態方法的信息,請查看[*標準類型層次*](#)中標準類型層次的文檔。
2.2版中新增。
2.4版中的新變化:添加函數裝飾器語法。
str(*object=''*)
返回一個字符串,包含對象的友好的可打印表示形式。對于字符串,它返回字符串本身。與repr(object)的區別是str(object)不會永遠試圖返回一個[eval()](# "eval")可接受的字符串;它的目標是返回一個可打印的字符串。如果沒有給出參數,則返回空字符串''。
關于字符串更多的信息請參閱[*序列類型 — str, unicode, list, tuple, bytearray, buffer, xrange*](#),它描述序列的函數(字符串是序列的一種),以及在[*String Methods*](#) 一節中描述的字符串自己的方法。若要輸出格式化的字符串,請使用模板字符串或在[*字符串格式化操作*](#)一節中描述的%操作符。另外可參閱[*字符串服務*](#)一節。另請參閱[unicode()](# "unicode")。
sum(*iterable*[, *start*])
將*start*以及*iterable*的元素從左向右相加并返回總和。*start*默認為0。*iterable*的元素通常是數字,start值不允許是一個字符串。
對于某些使用場景,有比[sum()](# "sum")更好的選擇。連接字符串序列的首選和快速的方式是調用''.join(sequence)。如要相加擴展精度的浮點數,請參閱[math.fsum()](# "math.fsum")。若要連接一系列的可迭代量,可以考慮使用[itertools.chain()](# "itertools.chain")。
2.3版中新增。
super(*type*[, *object-or-type*])
返回一個代理對象,這個對象指派方法給一個父類或者同*類*.這對進入類中被覆蓋的繼承方法非常有用。搜索順序和 [getattr()](# "getattr")?一樣。而它自己的?*類型* 則被忽略。
類型的?[__mro__](# "class.__mro__") 方法 *type* 羅列了被[getattr()](# "getattr") 和 [super()](# "super"). 用來搜索順序的解決方法。The attribute is dynamic and can change whenever the inheritance hierarchy is updated.
If the second argument is omitted, the super object returned is unbound.If the second argument is an object, isinstance(obj,type) must be true.If the second argument is a type, issubclass(type2,type) must be true (this is useful for classmethods).
Note
[super()](# "super") only works for [*new-style class*](#)es.
There are two typical use cases for *super*.In a class hierarchy with single inheritance, *super* can be used to refer to parent classes without naming them explicitly, thus making the code more maintainable.This use closely parallels the use of *super* in other programming languages.
The second use case is to support cooperative multiple inheritance in a dynamic execution environment.This use case is unique to Python and is not found in statically compiled languages or languages that only support single inheritance.This makes it possible to implement “diamond diagrams” where multiple base classes implement the same method.Good design dictates that this method have the same calling signature in every case (because the order of calls is determined at runtime, because that order adapts to changes in the class hierarchy, and because that order can include sibling classes that are unknown prior to runtime).
For both use cases, a typical superclass call looks like this:
~~~
class C(B):
def method(self, arg):
super(C, self).method(arg)
~~~
Note that [super()](# "super") is implemented as part of the binding process for explicit dotted attribute lookups such as super().__getitem__(name).It does so by implementing its own [__getattribute__()](# "object.__getattribute__") method for searching classes in a predictable order that supports cooperative multiple inheritance.Accordingly, [super()](# "super") is undefined for implicit lookups using statements or operators such as super()[name].
Also note that [super()](# "super") is not limited to use inside methods.The two argument form specifies the arguments exactly and makes the appropriate references.
For practical suggestions on how to design cooperative classes using [super()](# "super"), see [guide to using super()](http://rhettinger.wordpress.com/2011/05/26/super-considered-super/).
2.2版中新增。
tuple([*iterable*])
返回一個元組,其元素及順序與*iterable*的元素相同。*iterable*可以是一個序列、支持迭代操作的容器或迭代器對象。如果*iterable*已經是一個元組,它將被原樣返回。例如,tuple('abc')返回('a','b','c'),tuple([1,2,3])返回(1,2,3)。如果沒有給出參數,則返回一個空的元組()。
[tuple](# "tuple")是一個不可變序列類型,其文檔在[*序列類型 — str, unicode, list, tuple, bytearray, buffer, xrange*](#)。關于其它容器,請參閱內建的[dict](# "dict")、[list](# "list")和[set](# "set")類以及[collections](# "collections: High-performance datatypes")模塊。
type(*object*)type(*name*, *bases*, *dict*)
只有一個參數時,返回*object*的類型。返回值是一個類型對象。建議使用內建函數[isinstance()](# "isinstance")測試一個對象的類型。
帶有三個參數時,返回一個新的類型對象。它本質上是[class](#)語句的動態形式。*name*字符串是類的名字且將成為[__name__](# "class.__name__")屬性;*bases*元組逐條列舉基類并成為[__bases__](# "class.__bases__")屬性;*dict*字典是包含類體定義的命名空間并成為[__dict__](# "object.__dict__")屬性。例如,下面的兩條語句創建完全相同的[type](# "type")對象:
~~~
>>> class X(object):
... a = 1
...
>>> X = type('X', (object,), dict(a=1))
~~~
版本2.2中新增。
unichr(*i*)
返回Unicode碼為整數*i*的Unicode字符。例如,unichr(97)返回字符串u'a'。這是Unicode字符串[ord()](# "ord")的反轉。其參數合法的范圍取決于Python是如何配置的 – 它可以是UCS2 [0..0xFFFF] 或者UCS4 [0..0x10FFFF]。否則引發[ValueError](# "exceptions.ValueError")。對于ASCII和8比特字符串,請參閱[chr()](# "chr")。
2.0版中新增。
unicode(*object=''*)unicode(*object*[, *encoding*[, *errors*]])
使用下面的一種模式返回*object*的Unicode版字符串:
If *encoding* and/or *errors* are given, unicode() will decode the object which can either be an 8-bit string or a character buffer using the codec for *encoding*.The *encoding* parameter is a string giving the name of an encoding;if the encoding is not known, [LookupError](# "exceptions.LookupError") is raised.Error handling is done according to *errors*;this specifies the treatment of characters which are invalid in the input encoding.If *errors* is 'strict' (the default), a [ValueError](# "exceptions.ValueError") is raised on errors, while a value of 'ignore' causes errors to be silently ignored, and a value of 'replace' causes the official Unicode replacement character, U+FFFD, to be used to replace input characters which cannot be decoded.See also the [codecs](# "codecs: Encode and decode data and streams.") module.
If no optional parameters are given, unicode() will mimic the behaviour of str() except that it returns Unicode strings instead of 8-bit strings.More precisely, if *object* is a Unicode string or subclass it will return that Unicode string without any additional decoding applied.
For objects which provide a [__unicode__()](# "object.__unicode__") method, it will call this method without arguments to create a Unicode string.For all other objects, the 8-bit string version or representation is requested and then converted to a Unicode string using the codec for the default encoding in 'strict' mode.
For more information on Unicode strings see [*Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange*](#) which describes sequence functionality (Unicode strings are sequences), and also the string-specific methods described in the [*String Methods*](#) section.To output formatted strings use template strings or the % operator described in the [*String Formatting Operations*](#) section.In addition see the [*String Services*](#) section.See also [str()](# "str").
2.0版中新增。
2.2版中的變化:Support for [__unicode__()](# "object.__unicode__") added.
vars([*object*])
返回模塊、類、實例或其它任何具有__dict__屬性的對象的[__dict__](# "object.__dict__")屬性。
模塊和實例這樣的對象具有可更新的__dict__屬性;然而,其它對象可能對它們的__dict__屬性具有寫限制(例如,新式類使用dictproxy 來防止直接的字典更新)。
如果不帶參數,則[vars()](# "vars")的行為類似[locals()](# "locals")。注意,局部字典只用于讀取因為對局部字典的更新被忽略。
xrange(*stop*)xrange(*start*, *stop*[, *step*])
該函數與[range()](# "range")非常相似,但是它返回一個[*xrange 對象*](#)而不是一個列表。這是一個惰性的序列類型,它生成與對應的列表相同的值但不會真正同時一起存儲它們。[xrange()](# "xrange")相比[range()](# "range")的優點不大(因為[xrange()](# "xrange")仍然必須創建需要的值),除非在內存緊張的機器上使用一個非常大的range或者range的所有元素從不會使用(例如當循環經常被[break](#)終止)。關于xrange對象的更多對象,請參閱[*XRange 類型*](#)和[*序列類型— str, unicode, list, tuple, bytearray, buffer, xrange*](#)。
**CPython實現細節:**[xrange()](# "xrange")的設計意圖是簡單而快速。具體的實現可能強加各種限制以實現這點。Python的C實現限制所有的參數為C的原生長整型(Python的“短”整數),且要求元素的個數適合一個C的原生長整型。如果需要一個更大的range,可以使用[itertools](# "itertools: Functions creating iterators for efficient looping.")模塊創建一個另外的版本:islice(count(start,step),(stop-start+step-1+2*(step<0))//step)。
zip([*iterable*, *...*])
該函數返回一個元組的列表,其中第*i*個元組包含每個參數序列的第*i*個元素。返回的列表長度被截斷為最短的參數序列的長度。當多個參數都具有相同的長度時,[zip()](# "zip")類似于帶有一個初始參數為None的[map()](# "map")。只有一個序列參數時,它返回一個1元組的列表。沒有參數時,它返回一個空的列表。
可以保證迭代按從左向右的計算順序。這使得使用zip(*[iter(s)]*n)來將一系列數據分類歸并為長度為n的組成為習慣用法。
[zip()](# "zip")與 * 操作符一起可以用來unzip 一個列表:
~~~
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zipped)
>>> x == list(x2) and y == list(y2)
True
~~~
版本2.0中新增。
2.4版中的變化:以前,[zip()](# "zip")要求至少一個參數,且zip()將引發[TypeError](# "exceptions.TypeError")而不是一個空序列。
__import__(*name*[, *globals*[, *locals*[, *fromlist*[, *level*]]]])
注意
與[importlib.import_module()](# "importlib.import_module")不同,這是一個高級的函數,不會在日常的Python變成中用到,。
This function is invoked by the [import](#) statement.It can be replaced (by importing the [__builtin__](# "__builtin__: The module that provides the built-in namespace.") module and assigning to __builtin__.__import__) in order to change semantics of the [import](#) statement, but nowadays it is usually simpler to use import hooks (see [**PEP 302**](http://www.python.org/dev/peps/pep-0302)).Direct use of [__import__()](# "__import__") is rare, except in cases where you want to import a module whose name is only known at runtime.
The function imports the module *name*, potentially using the given *globals* and *locals* to determine how to interpret the name in a package context.The *fromlist* gives the names of objects or submodules that should be imported from the module given by *name*.The standard implementation does not use its *locals* argument at all, and uses its *globals* only to determine the package context of the [import](#) statement.
*level* specifies whether to use absolute or relative imports.The default is -1 which indicates both absolute and relative imports will be attempted.0 means only perform absolute imports.Positive values for *level* indicate the number of parent directories to search relative to the directory of the module calling [__import__()](# "__import__").
When the *name* variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, *not* the module named by *name*.However, when a non-empty *fromlist* argument is given, the module named by *name* is returned.
For example, the statement importspam results in bytecode resembling the following code:
~~~
spam = __import__('spam', globals(), locals(), [], -1)
~~~
The statement importspam.ham results in this call:
~~~
spam = __import__('spam.ham', globals(), locals(), [], -1)
~~~
Note how [__import__()](# "__import__") returns the toplevel module here because this is the object that is bound to a name by the [import](#) statement.
On the other hand, the statement fromspam.hamimporteggs,sausageassaus results in
~~~
_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], -1)
eggs = _temp.eggs
saus = _temp.sausage
~~~
Here, the spam.ham module is returned from [__import__()](# "__import__").From this object, the names to import are retrieved and assigned to their respective names.
如果你只是簡單地想依據名字導入一個模塊,請使用[importlib.import_module()](# "importlib.import_module")。
2.5版中的變化:添加level參數。
2.5版中的變化:添加關鍵字參數的支持。
- Python 2 教程
- 1. 吊吊你的胃口
- 2. Python 解釋器
- 3. Python簡介
- 4. 控制流
- 5. 數據結構
- 6. 模塊
- 7. 輸入和輸出
- 8. 錯誤和異常
- 9. 類
- 10. 標準庫概覽
- 11. 標準庫概覽 — 第II部分
- 12.現在怎么辦?
- 13. 交互式輸入的編輯和歷史記錄
- 14. 浮點數運算:問題和局限
- Python 2 標準庫
- 1. 引言
- 2. 內建函數
- 3. 不太重要的內建函數
- 4. 內建的常量
- 5. 內建的類型
- 6. 內建的異常
- 7. String Services
- 8. Data Types
- 9. Numeric and Mathematical Modules
- 10. File and Directory Access
- 11. Data Persistence
- 13. File Formats
- 14. Cryptographic Services
- 15. Generic Operating System Services
- 16. Optional Operating System Services
- 17. Interprocess Communication and Networking
- 18. Internet Data Handling
- 20. Internet Protocols and Support
- 26. Debugging and Profiling
- 28. Python Runtime Services
- Python 2 語言參考
- 1. 簡介
- 2. 詞法分析
- 3. 數據模型
- 4. 執行模型
- 5. 表達式
- 6. 簡單語句
- 7. 復合語句
- 8. 頂層的組件
- 9. 完整的語法規范
- Python 3 教程
- 1. 引言
- 2. Python 解釋器
- 3. Python簡介
- 4. 控制流
- 5. 數據結構
- 6. 模塊
- 7. 輸入和輸出
- 8. 錯誤和異常
- 9. 類
- 10. 標準庫概覽
- 11. 標準庫概覽 — 第II部分
- 12.現在怎么辦?
- 13. 交互式輸入的編輯和歷史記錄
- 14. 浮點數運算:問題和局限