Python 解释器有很多始终可用的内置函数。在此按字母顺序列表它们。
|
内置函数 |
||||
|---|---|---|---|---|
In addition, there are other four built-in functions that are no longer considered essential:
apply()
,
buffer()
,
coerce()
,和
intern()
. They are documented in the
非必需内置函数
章节。
abs
(
x
)
¶
Return the absolute value of a number. The argument may be a plain or long integer or a floating point number. If the argument is a complex number, its magnitude is returned.
all
(
iterable
)
¶
返回
True
若所有元素在
iterable
为 true (或者若可迭代为空)。相当于:
def all(iterable): for element in iterable: if not element: return False return True
2.5 版新增。
any
(
iterable
)
¶
返回
True
若任何元素在
iterable
为 True。若可迭代为空,返回
False
。相当于:
def any(iterable): for element in iterable: if element: return True return False
2.5 版新增。
basestring
(
)
¶
此抽象类型是超类对于
str
and
unicode
. It cannot be called or instantiated, but it can be used to test whether an object is an instance of
str
or
unicode
.
isinstance(obj,
basestring)
相当于
isinstance(obj, (str, unicode))
.
2.3 版新增。
bin
(
x
)
¶
Convert an integer number to a binary string. The result is a valid Python expression. If
x
不是 Python
int
对象,它必须定义
__index__()
method that returns an integer.
2.6 版新增。
bool
(
[
x
]
)
¶
返回布尔值,即:
True
or
False
.
x
is converted using the standard truth testing procedure. If
x
为 false 或被省略,这返回
False
;否则返回
True
.
bool
is also a class, which is a subclass of
int
. Class
bool
cannot be subclassed further. Its only instances are
False
and
True
.
New in version 2.2.1.
Changed in version 2.3:
If no argument is given, this function returns
False
.
bytearray
(
[
source
[
,
encoding
[
,
errors
]
]
]
)
¶
返回新的字节数组。
bytearray
类是在 0 <= x < 256 范围的可变整数序列。它拥有可变序列的大多数通常方法,描述在
可变序列类型
,及大多数方法如
str
类型拥有的,见
字符串方法
.
可选 source 参数可以用于按几种不同方式初始化数组:
若它是
unicode
,还必须给出
encoding
(和可选,
errors
) 参数;
bytearray()
then converts the unicode to bytes using
unicode.encode()
.
若它是 integer ,数组将拥有该大小并将采用 Null 字节进行初始化。
若它是对象且符合 buffer interface, a read-only buffer of the object will be used to initialize the bytes array.
若它是
iterable
,它必须是整数的可迭代在范围
0 <= x < 256
,用作数组的初始内容。
没有自变量,创建 0 大小的数组。
2.6 版新增。
callable
(
对象
)
¶
返回
True
若
object
自变量看起来可调用,
False
if not. If this returns true, it is still possible that a call fails, but if it is false, calling
object
will never succeed. Note that classes are callable (calling a class returns a new instance); class instances are callable if they have a
__call__()
方法。
chr
(
i
)
¶
Return a string of one character whose ASCII code is the integer
i
。例如,
chr(97)
返回字符串
'a'
。这是逆
ord()
. The argument must be in the range [0..255], inclusive;
ValueError
会被引发若
i
is outside that range. See also
unichr()
.
classmethod
(
function
)
¶
Return a class method for function .
类方法接收类作为隐式第一自变量,就像实例方法接收实例。要声明类方法,使用此习语:
class C(object): @classmethod def f(cls, arg1, arg2, ...): ...
The
@classmethod
形式是函数
装饰器
– 见
函数定义
了解细节。
类方法可以被调用在类 (譬如
C.f()
) 或在实例 (譬如
C().f()
)。实例被忽略,除它的类外。若派生类调用类方法,则派生类对象作为隐式第一自变量被传递。
类方法不同于 C++ 或 Java 静态方法。若想要这些,见
staticmethod()
.
For more information on class methods, see 标准类型层次结构 .
2.2 版新增。
2.4 版改变: 添加函数装饰器句法。
cmp
(
x
,
y
)
¶
Compare the two objects
x
and
y
and return an integer according to the outcome. The return value is negative if
x < y
, zero if
x == y
and strictly positive if
x > y
.
compile
(
source
,
filename
,
mode
[
,
flags
[
,
dont_inherit
]
]
)
¶
编译
source
into a code or AST object. Code objects can be executed by an
exec
statement or evaluated by a call to
eval()
.
source
can either be a Unicode string, a
Latin-1
encoded string or an AST object. Refer to the
ast
模块文档编制,了解如何操控 AST 对象的有关信息。
The
filename
自变量是应该给出从中读取代码的文件;传递一些可识别值,若不从文件读取 (
'<string>'
很常用)。
The
mode
自变量指定必须编译哪种代码;它可以是
'exec'
if
source
由一系列语句组成,
'eval'
若它由单个表达式组成,或
'single'
若它由单个交互式语句组成 (后一种情况,评估为某物的表达式语句而不是
None
会被打印)。
可选自变量
flags
and
dont_inherit
control which future statements (see
PEP 236
) affect the compilation of
source
. If neither is present (or both are zero) the code is compiled with those future statements that are in effect in the code that is calling
compile()
。若
flags
自变量有给定且
dont_inherit
is not (or is zero) then the future statements specified by the
flags
自变量的使用,除无论如何会使用的哪些外。若
dont_inherit
是非 0 整数那么
flags
argument is it – the future statements in effect around the call to compile are ignored.
Future statements are specified by bits which can be bitwise ORed together to specify multiple statements. The bitfield required to specify a given feature can be found as the
compiler_flag
属性在
_Feature
实例在
__future__
模块。
此函数引发
SyntaxError
若编译源无效,和
TypeError
若 source 包含 null 字节。
若想要将 Python 代码剖析成 AST 表示,见
ast.parse()
.
注意
当编译具有多行代码的字符串按
'single'
or
'eval'
模式,输入必须以至少一换行符结尾。这促进检测不完整完整和完整语句在
code
模块。
警告
由于 Python 的 AST (抽象句法树) 编译器的堆栈深度局限性,当编译到 AST 对象时,采用足够大的 (复杂) 字符串 Python 解释器可能崩溃。
Changed in version 2.3: The flags and dont_inherit 自变量被添加。
2.6 版改变: Support for compiling AST objects.
2.7 版改变:
Allowed use of Windows and Mac newlines. Also input in
'exec'
mode does not have to end in a newline anymore.
complex
(
[
real
[
,
imag
]
]
)
¶
返回复数具有值
real
+
imag
*1j or convert a string or number to a complex number. If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric type (including complex). If
imag
is omitted, it defaults to zero and the function serves as a numeric conversion function like
int()
,
long()
and
float()
. If both arguments are omitted, returns
0j
.
注意
当从字符串转换时,字符串必须不包含空白围绕中心
+
or
-
运算符。例如,
complex('1+2j')
很好,但
complex('1 + 2j')
引发
ValueError
.
复杂类型的描述在 Numeric Types — int, float, long, complex .
delattr
(
对象
,
名称
)
¶
这相对于
setattr()
。自变量是对象和字符串。字符串必须是对象属性名称之一。函数将删除命名属性,若提供的对象允许。例如,
delattr(x, 'foobar')
相当于
del x.foobar
.
dict
(
**kwarg
)
dict
(
映射
,
**kwarg
)
dict
(
iterable
,
**kwarg
)
创建新字典。
dict
对象是字典类。见
dict
and
映射类型 — dict
有关此类的文档编制。
对于其它容器,见内置
list
,
set
,和
tuple
类,及
collections
模块。
dir
(
[
对象
]
)
¶
不带自变量,返回当前本地作用域中的名称列表。带自变量,试图返回该对象的有效属性列表。
若对象拥有方法名
__dir__()
,会调用此方法,且必须返回属性列表。这允许对象实现自定义
__getattr__()
or
__getattribute__()
函数以定制方式
dir()
报告它们的属性。
若对象不提供
__dir__()
, the function tries its best to gather information from the object’s
__dict__
attribute, if defined, and from its type object. The resulting list is not necessarily complete, and may be inaccurate when the object has a custom
__getattr__()
.
默认
dir()
mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:
If the object is a module object, the list contains the names of the module’s attributes.
If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.
Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.
结果列表按字母顺序排序。例如:
>>> 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()
is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.
divmod
(
a
,
b
)
¶
Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using long division. With mixed operand types, the rules for binary arithmetic operators apply. For plain and long integers, the result is the same as
(a // b, a % b)
. For floating point numbers the result is
(q, a % b)
,其中
q
通常是
math.floor(a / b)
but may be 1 less than that. In any case
q * b + a % b
is very close to
a
,若
a % b
is non-zero it has the same sign as
b
,和
0 <= abs(a % b)
<
abs(b)
.
Changed in version 2.3:
使用
divmod()
with complex numbers is deprecated.
enumerate
(
sequence
,
start=0
)
¶
返回枚举对象。
sequence
必须是序列,
iterator
,或支持迭代的某些其它对象。
next()
方法对于迭代器返回通过
enumerate()
返回元组包含计数 (从
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 版改变: The start 参数被添加。
eval
(
表达式
[
,
globals
[
,
locals
]
]
)
¶
The arguments are a Unicode or Latin-1 encoded string and optional globals and locals. If provided, globals 必须是字典。若有提供, locals 可以是任何映射对象。
2.4 版改变: formerly locals was required to be a dictionary.
The
表达式
argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the
globals
and
locals
dictionaries as global and local namespace. If the
globals
dictionary is present and lacks ‘__builtins__’, the current globals are copied into
globals
before
表达式
is parsed. This means that
表达式
normally has full access to the standard
__builtin__
module and restricted environments are propagated. If the
locals
dictionary is omitted it defaults to the
globals
dictionary. If both dictionaries are omitted, the expression is executed in the environment where
eval()
is called. The return value is the result of the evaluated expression. Syntax errors are reported as exceptions. Example:
>>> x = 1
>>> print eval('x+1')
2
This function can also be used to execute arbitrary code objects (such as those created by
compile()
). In this case pass a code object instead of a string. If the code object has been compiled with
'exec'
作为
mode
自变量,
eval()
的返回值将是
None
.
提示:语句动态执行的支持通过
exec
statement. Execution of statements from a file is supported by the
execfile()
函数。
globals()
and
locals()
functions returns the current global and local dictionary, respectively, which may be useful to pass around for use by
eval()
or
execfile()
.
见
ast.literal_eval()
了解可以安全评估仅包含文字的字符串表达式的函数。
execfile
(
filename
[
,
globals
[
,
locals
]
]
)
¶
This function is similar to the
exec
statement, but parses a file instead of a string. It is different from the
import
statement in that it does not use the module administration — it reads the file unconditionally and does not create a new module.
1
The arguments are a file name and two optional dictionaries. The file is parsed and evaluated as a sequence of Python statements (similarly to a module) using the globals and locals dictionaries as global and local namespace. If provided, locals can be any mapping object. Remember that at module level, globals and locals are the same dictionary. If two separate objects are passed as globals and locals , the code will be executed as if it were embedded in a class definition.
2.4 版改变: formerly locals was required to be a dictionary.
若
locals
dictionary is omitted it defaults to the
globals
dictionary. If both dictionaries are omitted, the expression is executed in the environment where
execfile()
is called. The return value is
None
.
注意
默认
locals
作用的描述按函数
locals()
下文:修改默认
locals
字典不应尝试。传递明确
locals
字典若需要查看代码效果在
locals
后于函数
execfile()
返回。
execfile()
cannot be used reliably to modify a function’s locals.
file
(
名称
[
,
mode
[
,
buffering
]
]
)
¶
Constructor function for the
file
type, described further in section
文件对象
. The constructor’s arguments are the same as those of the
open()
built-in function described below.
When opening a file, it’s preferable to use
open()
instead of invoking this constructor directly.
file
is more suited to type testing (for example, writing
isinstance(f, file)
).
2.2 版新增。
filter
(
function
,
iterable
)
¶
Construct a list from those elements of
iterable
其中
function
返回 True。
iterable
可以是序列、支持迭代的容器或迭代器。若
iterable
is a string or a tuple, the result also has that type; otherwise it is always a list. If
function
is
None
, the identity function is assumed, that is, all elements of
iterable
that are false are removed.
注意,
filter(function, iterable)
相当于
[item for item in
iterable
if
function(item)]
若函数不为
None
and
[item for item
in
iterable
if
item]
若函数为
None
.
见
itertools.ifilter()
and
itertools.ifilterfalse()
for iterator versions of this function, including a variation that filters for elements where the
function
返回 False。
float
(
[
x
]
)
¶
返回浮点数构造自数字或字符串 x .
If the argument is a string, it must contain a possibly signed decimal or floating point number, possibly embedded in whitespace. The argument may also be [+|-]nan or [+|-]inf. Otherwise, the argument may be a plain or long integer or a floating point number, and a floating point number with the same value (within Python’s floating point precision) is returned. If no argument is given, returns
0.0
.
注意
When passing in a string, values for NaN and Infinity may be returned, depending on the underlying C library. Float accepts the strings nan, inf and -inf for NaN and positive or negative infinity. The case and a leading + are ignored as well as a leading - is ignored for NaN. Float always represents NaN and infinity as nan, inf or -inf.
浮点类型的描述在 Numeric Types — int, float, long, complex .
format
(
值
[
,
format_spec
]
)
¶
转换 value 按 "格式化" 表示,如控制通过 format_spec 。解释 format_spec 将从属其类型对于 value 自变量,不管怎样,大多数内置类型可以使用标准格式化句法: 格式规范迷你语言 .
注意
format(value, format_spec)
merely calls
value.__format__(format_spec)
.
2.6 版新增。
frozenset
(
[
iterable
]
)
返回新的
frozenset
对象,可选采用元素取自
iterable
.
frozenset
是内置类。见
frozenset
and
集类型 — set、frozenset
有关此类的文档编制。
对于其它容器,见内置
set
,
list
,
tuple
,和
dict
类,及
collections
模块。
2.4 版新增。
getattr
(
对象
,
名称
[
,
default
]
)
¶
返回命名属性的值为
object
.
name
必须是字符串。若字符串是对象属性名称之一,结果就是该属性的值。例如,
getattr(x, 'foobar')
相当于
x.foobar
。若命名属性不存在,
default
被返回若有提供,否则
AttributeError
被引发。
globals
(
)
¶
返回表示当前全局符号表的字典。这始终是当前模块的字典 (在函数或方法内,这是定义它的模块,而不是调用它的模块)。
hasattr
(
对象
,
名称
)
¶
自变量是对象和字符串。结果为
True
若字符串是对象某一属性的名称,
False
若不是。(这被实现通过调用
getattr(object, name)
and seeing whether it raises an exception or not.)
hash
(
对象
)
¶
返回对象的哈希值 (若有的话)。哈希值是整数。它们用于在字典查找期间快速比较字典键。比较相等的数值拥有相同哈希值 (即使它们是不同类型,如 1 和 1.0 的情况)。
help
(
[
对象
]
)
¶
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.
此函数已添加到内置名称空间通过
site
模块。
2.2 版新增。
hex
(
x
)
¶
Convert an integer number (of any size) to a lowercase hexadecimal string prefixed with “0x”, for example:
>>> hex(255)
'0xff'
>>> hex(-42)
'-0x2a'
>>> hex(1L)
'0x1L'
If x is not a Python
int
or
long
object, it has to define a __hex__() method that returns a string.
另请参阅
int()
了解将十六进制字符串转换为以 16 为基的整数。
注意
要获得浮点数的十六进制字符串表示,使用
float.hex()
方法。
2.4 版改变: Formerly only returned an unsigned literal.
id
(
对象
)
¶
Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same
id()
值。
CPython 实现细节: 这是对象在内存中的地址。
input
(
[
prompt
]
)
¶
相当于
eval(raw_input(prompt))
.
This function does not catch user errors. If the input is not syntactically valid, a
SyntaxError
will be raised. Other exceptions may be raised if there is an error during evaluation.
若
readline
模块被加载,则
input()
将使用它来提供详尽行编辑和历史特征。
Consider using the
raw_input()
function for general input from users.
int
(
x=0
)
¶
int
(
x
,
base=10
)
返回的整数对象构造自数字或字符串
x
,或返回
0
若自变量未给定。若
x
is a number, it can be a plain integer, a long integer, or a floating point number. If
x
is floating point, the conversion truncates towards zero. If the argument is outside the integer range, the function returns a long object instead.
若
x
不是数字或者若
base
有给定,那么
x
must be a string or Unicode object representing an
整数文字
按基数
base
. Optionally, the literal can be preceded by
+
or
-
(之间没有空格) 并以空白环绕。base-n 文字由数字 0 到 n-1 组成,采用
a
to
z
(或
A
to
Z
) 拥有值 10 到 35。默认
base
为 10。允许值为 0 和 2-36。Base-2、-8 和 -16 文字可以可选前缀
0b
/
0B
,
0o
/
0O
/
0
,或
0x
/
0X
, as with integer literals in code. Base 0 means to interpret the string exactly as an integer literal, so that the actual base is 2, 8, 10, or 16.
整数类型的描述在 Numeric Types — int, float, long, complex .
isinstance
(
对象
,
classinfo
)
¶
返回 True 若
object
自变量是实例对于
classinfo
自变量,或 (直接、间接或
virtual
) subclass thereof. Also return true if
classinfo
is a type object (new-style class) and
object
is an object of that type or of a (direct, indirect or
virtual
) 其子类。若
object
is not a class instance or an object of the given type, the function always returns false. If
classinfo
is a tuple of class or type objects (or recursively, other such tuples), return true if
object
is an instance of any of the classes or types. If
classinfo
is not a class, type, or tuple of classes, types, and such tuples, a
TypeError
异常被引发。
2.2 版改变: Support for a tuple of type information was added.
issubclass
(
class
,
classinfo
)
¶
返回 True 若
class
是子类 (直接、间接或
virtual
) of
classinfo
。类被认为是自身的子类。
classinfo
可以是类对象元组,在这种情况下,每个条目在
classinfo
将被校验。在任何其它情况下,
TypeError
异常被引发。
Changed in version 2.3: Support for a tuple of type information was added.
iter
(
o
[
,
sentinel
]
)
¶
返回
iterator
对象。第一自变量的解释非常不同,从属存在的第二自变量。没有第二自变量,
o
必须是支持迭代协议的集合对象 (
__iter__()
方法),或它必须支持序列协议 (
__getitem__()
方法采用的整数自变量开始于
0
)。若它不支持这些协议,
TypeError
被引发。若第 2 自变量
sentinel
有给定,那么
o
必须是可调用对象。在这种情况下创建的迭代器将调用
o
不采用自变量每次调用其
next()
方法;若返回值等于
sentinel
,
StopIteration
将被引发,否则会返回值。
第 2 种形式的有用应用程序对于
iter()
is to read lines of a file until a certain line is reached. The following example reads a file until the
readline()
method returns an empty string:
with open('mydata.txt') as fp: for line in iter(fp.readline, ''): process_line(line)
2.2 版新增。
len
(
s
)
¶
返回对象的长度 (项数)。自变量可以是序列 (譬如:字符串、字节、元组、列表或范围) 或集合 (譬如:字典、集或冻结集)。
list
(
[
iterable
]
)
Return a list whose items are the same and in the same order as
iterable
’s items.
iterable
may be either a sequence, a container that supports iteration, or an iterator object. If
iterable
is already a list, a copy is made and returned, similar to
iterable[:]
. For instance,
list('abc')
返回
['a', 'b', 'c']
and
list( (1, 2, 3) )
返回
[1, 2, 3]
. If no argument is given, returns a new empty list,
[]
.
list
is a mutable sequence type, as documented in
Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange
. For other containers see the built in
dict
,
set
,和
tuple
类,和
collections
模块。
locals
(
)
¶
更新并返回表示当前本地符号表的字典。自由变量的返回是通过
locals()
当在函数块中而不是类块中调用它时。
注意
此词典的内容不应被修改;更改可能不影响由解释器使用的局部变量和自由变量的值。
long
(
x=0
)
¶
long
(
x
,
base=10
)
Return a long integer object constructed from a string or number
x
. If the argument is a string, it must contain a possibly signed number of arbitrary size, possibly embedded in whitespace. The
base
argument is interpreted in the same way as for
int()
, and may only be given when
x
is a string. Otherwise, the argument may be a plain or long integer or a floating point number, and a long integer with the same value is returned. Conversion of floating point numbers to integers truncates (towards zero). If no arguments are given, returns
0L
.
The long type is described in Numeric Types — int, float, long, complex .
map
(
function
,
iterable
,
...
)
¶
应用
function
到每项为
iterable
and return a list of the results. If additional
iterable
自变量有传递,
function
must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with
None
items. If
function
is
None
, the identity function is assumed; if there are multiple arguments,
map()
returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The
iterable
arguments may be a sequence or any iterable object; the result is always a list.
max
(
iterable
[
,
key
]
)
¶
max
(
arg1
,
arg2
,
*args
[
,
key
]
)
返回可迭代中的最大项 (或 2 个或多个自变量中的最大项)。
If one positional argument is provided, iterable must be a non-empty iterable (such as a non-empty string, tuple or list). The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned.
可选
key
argument specifies a one-argument ordering function like that used for
list.sort()
。
key
argument, if supplied, must be in keyword form (for example,
max(a,b,c,key=func)
).
Changed in version 2.5: Added support for the optional key 自变量。
memoryview
(
obj
)
返回从给定自变量创建的内存视图对象。见 memoryview 类型 了解更多信息。
min
(
iterable
[
,
key
]
)
¶
min
(
arg1
,
arg2
,
*args
[
,
key
]
)
返回可迭代中的最小项 (或 2 个或多个自变量中的最小项)。
If one positional argument is provided, iterable must be a non-empty iterable (such as a non-empty string, tuple or list). The smallest item in the iterable is returned. If two or more positional arguments are provided, the smallest of the positional arguments is returned.
可选
key
argument specifies a one-argument ordering function like that used for
list.sort()
。
key
argument, if supplied, must be in keyword form (for example,
min(a,b,c,key=func)
).
Changed in version 2.5: Added support for the optional key 自变量。
next
(
iterator
[
,
default
]
)
¶
检索下一项从
iterator
通过调用其
next()
方法。若
default
有给定,返回它若迭代器耗尽,否则
StopIteration
被引发。
2.6 版新增。
object
¶
返回新的无特征对象。
object
is a base for all new style classes. It has the methods that are common to all instances of new style classes.
2.2 版新增。
Changed in version 2.3: This function does not accept any arguments. Formerly, it accepted arguments but ignored them.
oct
(
x
)
¶
Convert an integer number (of any size) to an octal string. The result is a valid Python expression.
2.4 版改变: Formerly only returned an unsigned literal.
open
(
名称
[
,
mode
[
,
buffering
]
]
)
¶
Open a file, returning an object of the
file
type described in section
文件对象
. If the file cannot be opened,
IOError
is raised. When opening a file, it’s preferable to use
open()
instead of invoking the
file
构造函数直接。
The first two arguments are the same as for
stdio
’s
fopen()
:
name
is the file name to be opened, and
mode
is a string indicating how the file is to be opened.
The most commonly-used values of
mode
are
'r'
for reading,
'w'
for writing (truncating the file if it already exists), and
'a'
以供追加 (在
some
Unix systems means that
all
writes append to the end of the file regardless of the current seek position). If
mode
is omitted, it defaults to
'r'
. The default is to use text mode, which may convert
'\n'
characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append
'b'
到
mode
value to open the file in binary mode, which will improve portability. (Appending
'b'
is useful even on systems that don’t treat binary and text files differently, where it serves as documentation.) See below for more possible values of
mode
.
可选 buffering argument specifies the file’s desired buffer size: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size (in bytes). A negative buffering means to use the system default, which is usually line buffered for tty devices and fully buffered for other files. If omitted, the system default is used. 2
模式
'r+'
,
'w+'
and
'a+'
open the file for updating (reading and writing); note that
'w+'
truncates the file. Append
'b'
to the mode to open the file in binary mode, on systems that differentiate between binary and text files; on systems that don’t have this distinction, adding the
'b'
不起作用。
In addition to the standard
fopen()
值
mode
可以是
'U'
or
'rU'
. Python is usually built with
通用换行符
support; supplying
'U'
opens the file as a text file, but lines may be terminated by any of the following: the Unix end-of-line convention
'\n'
, the Macintosh convention
'\r'
, or the Windows convention
'\r\n'
. All of these external representations are seen as
'\n'
by the Python program. If Python is built without universal newlines support a
mode
with
'U'
is the same as normal text mode. Note that file objects so opened also have an attribute called
newlines
which has a value of
None
(if no newlines have yet been seen),
'\n'
,
'\r'
,
'\r\n'
, or a tuple containing all the newline types seen.
Python enforces that the mode, after stripping
'U'
, begins with
'r'
,
'w'
or
'a'
.
Python provides many file handling modules including
fileinput
,
os
,
os.path
,
tempfile
,和
shutil
.
Changed in version 2.5: Restriction on first letter of mode string introduced.
ord
(
c
)
¶
Given a string of length one, return an integer representing the Unicode code point of the character when the argument is a unicode object, or the value of the byte when the argument is an 8-bit string. For example,
ord('a')
返回整数
97
,
ord(u'\u2020')
返回
8224
。这是逆
chr()
for 8-bit strings and of
unichr()
for unicode objects. If a unicode argument is given and Python was built with UCS2 Unicode, then the character’s code point must be in the range [0..65535] inclusive; otherwise the string length is two, and a
TypeError
会被引发。
pow
(
x
,
y
[
,
z
]
)
¶
返回
x
到幂
y
;若
z
存在,返回
x
到幂
y
,模
z
(计算更高效相比
pow(x, y) % z
)。2 自变量形式
pow(x, y)
相当于使用幂运算符:
x**y
.
The arguments must have numeric types. With mixed operand types, the coercion rules for binary arithmetic operators apply. For int and long int operands, the result has the same type as the operands (after coercion) unless the second argument is negative; in that case, all arguments are converted to float and a float result is delivered. For example,
10**2
返回
100
,但
10**-2
返回
0.01
. (This last feature was added in Python 2.2. In Python 2.1 and before, if both arguments were of integer types and the second argument was negative, an exception was raised.) If the second argument is negative, the third argument must be omitted. If
z
存在,
x
and
y
必须是整数类型,且
y
must be non-negative. (This restriction was added in Python 2.2. In Python 2.1 and before, floating 3-argument
pow()
returned platform-dependent results depending on floating-point rounding accidents.)
print
(
*objects
,
sep=' '
,
end='\n'
,
file=sys.stdout
)
¶
打印 对象 到流 file ,分隔通过 sep 且之后紧跟 end . sep , end and file ,若存在,必须以关键词自变量形式给出。
会将所有非关键自变量转换成字符串像
str()
所做的并写入流,分隔通过
sep
且之后紧跟
end
。两者
sep
and
end
必须为字符串;它们还可以为
None
,意味着使用默认值。若没有
对象
的给定,
print()
将仅仅写入
end
.
The
file
自变量必须是对象具有
write(string)
方法;若它不存在或为
None
,
sys.stdout
will be used. Output buffering is determined by
file
。使用
file.flush()
to ensure, for instance, immediate appearance on a screen.
注意
This function is not normally available as a built-in since the name
print
is recognized as the
print
statement. To disable the statement and use the
print()
function, use this future statement at the top of your module:
from __future__ import print_function
2.6 版新增。
property
(
[
fget
[
,
fset
[
,
fdel
[
,
doc
]
]
]
]
)
¶
Return a property attribute for
新样式类
es (classes that derive from
object
).
fget 是用于获取属性值的函数。 fset 是用于设置属性值的函数。 fdel 是用于删除属性值的函数。和 doc 为属性创建 docstring (文档字符串)。
典型用法是定义管理属性
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
将援引 getter,
c.x = value
将援引 setter 和
del c.x
deleter。
若给定,
doc
将是 property 属性的 docstring (文档字符串)。否则,特性将拷贝
fget
的文档字符串 (若存在)。这使之可能轻松创建只读特性使用
property()
作为
装饰器
:
class Parrot(object): def __init__(self): self._voltage = 100000 @property def voltage(self): """Get the current voltage.""" return self._voltage
The
@property
装饰器转换
voltage()
方法转换成具有相同名称的只读属性 getter,并设置文档字符串为
voltage
成 Get the current voltage (获取电流电压)。
property 对象拥有
getter
,
setter
,和
deleter
方法,可用作装饰器以创建将设为装饰函数,具有相应 accessor (访问器) 函数的特性副本。最好采用范例来解释这:
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
此代码与第 1 范例准确等价。确保赋予额外函数相同名称如原始特性 (
x
在此情况下)。
返回特性对象也拥有属性
fget
,
fset
,和
fdel
对应构造函数自变量。
2.2 版新增。
Changed in version 2.5: 使用 fget ’s docstring if no doc 给定。
2.6 版改变:
The
getter
,
setter
,和
deleter
attributes were added.
range
(
stop
)
¶
range
(
start
,
stop
[
,
step
]
)
This is a versatile function to create lists containing arithmetic progressions. It is most often used in
for
loops. The arguments must be plain integers. If the
step
argument is omitted, it defaults to
1
。若
start
argument is omitted, it defaults to
0
. The full form returns a list of plain integers
[start, start + step, start + 2 * step, ...]
。若
step
is positive, the last element is the largest
start + i * step
less than
stop
;若
step
is negative, the last element is the smallest
start + i *
step
greater than
stop
.
step
must not be zero (or else
ValueError
is raised). Example:
>>> 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
自变量存在,将不带结尾换行符将它写入标准输出。然后,函数从输入读取一行,将其转换为字符串 (去掉末尾换行符),并返回该字符串。
EOFError
被引发。范例:
>>> s = raw_input('--> ') --> Monty Python's Flying Circus >>> s "Monty Python's Flying Circus"
若
readline
模块被加载,则
raw_input()
将使用它来提供详尽行编辑和历史特征。
reduce
(
function
,
iterable
[
,
initializer
]
)
¶
应用
function
的 2 自变量的累积到项为
iterable
,从左到右,以便将可迭代缩减到单个值。例如,
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
计算
((((1+2)+3)+4)+5)
。左自变量
x
, is the accumulated value and the right argument,
y
, is the update value from the
iterable
. If the optional
initializer
is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If
initializer
未给定且
iterable
contains only one item, the first item is returned. Roughly equivalent to:
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 . The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter. The return value is the module object (the same as the module argument).
当
reload(module)
被执行:
Python modules’ code is recompiled and the module-level code reexecuted, defining a new set of objects which are bound to names in the module’s dictionary. The
init
函数对于扩展模块不会被 2 次调用。
如 Python 所有其它对象,旧对象仅在其引用计数降至 0 后才被回收。
更新模块名称空间中的名称,以指向任何新的 (或更改) 对象。
旧对象的其它引用 (譬如:模块外部名称) 不会重新绑定到新对象引用,且必须更新它们出现的每个名称空间,若期望。
有很多其它告诫:
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 generally not very useful to reload built-in or dynamically loaded modules. Reloading
sys
,
__main__
,
builtins
and other key modules is not recommended. In many cases 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()
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
(
对象
)
¶
Return a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function. 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()
, 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. A class can control what this function returns for its instances by defining a
__repr__()
方法。
reversed
(
seq
)
¶
返回反向
iterator
.
seq
必须是对象且有
__reversed__()
方法或支持序列协议 (
__len__()
方法和
__getitem__()
方法采用的整数自变量开始于
0
).
2.4 版新增。
2.6 版改变:
添加可能编写自定义
__reversed__()
方法。
round
(
编号
[
,
ndigits
]
)
¶
返回浮点值
number
四舍五入到
ndigits
digits after the decimal point. If
ndigits
is omitted, it defaults to zero. The result is a floating point number. 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 (so, for example,
round(0.5)
is
1.0
and
round(-0.5)
is
-1.0
).
注意
行为在
round()
对于浮点数可能出人意料:例如,
round(2.675, 2)
给出
2.67
而不是期望的
2.68
。这不是 Bug:事实是大多数十进制小数不能准确表示成浮点的结果。见
浮点算术:问题和局限性
了解更多信息。
set
(
[
iterable
]
)
返回新的
set
对象,可选采用元素取自
iterable
.
set
是内置类。见
set
and
集类型 — set、frozenset
有关此类的文档编制。
对于其它容器,见内置
frozenset
,
list
,
tuple
,和
dict
类,及
collections
模块。
2.4 版新增。
setattr
(
对象
,
名称
,
值
)
¶
这搭档
getattr()
。自变量是对象、字符串和任意值。字符串可以命名现有属性或新属性。函数将值赋值给属性,若提供对象允许。例如,
setattr(x, 'foobar', 123)
相当于
x.foobar = 123
.
slice
(
stop
)
¶
slice
(
start
,
stop
[
,
step
]
)
返回
slice
对象表示的索引集指定通过
range(start, stop, step)
。
start
and
step
自变量默认为
None
。切片对象拥有只读数据属性
start
,
stop
and
step
,仅仅返回自变量值 (或它们的默认值)。它们没有其它明确功能;不管怎样,它们可用于 Numerical Python 和其它第 3 方扩展。也会生成切片对象,当使用扩展索引句法时。例如:
a[start:stop:step]
or
a[start:stop, i]
。见
itertools.islice()
对于返回迭代器的替代版本。
sorted
(
iterable
[
,
cmp
[
,
key
[
,
reverse
]
]
]
)
¶
返回新的排序列表,项来自 iterable .
可选自变量
cmp
,
key
,和
reverse
有相同含义如那些对于
list.sort()
方法 (描述在章节
可变序列类型
).
cmp
specifies a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument:
cmp=lambda x,y: cmp(x.lower(), y.lower())
。默认值为
None
.
key
specifies a function of one argument that is used to extract a comparison key from each list element:
key=str.lower
。默认值为
None
(直接比较元素)。
reverse
是布尔值。若设为
True
,则对列表元素排序,就好像反转每一比较。
一般而言,
key
and
reverse
conversion processes are much faster than specifying an equivalent
cmp
function. This is because
cmp
is called multiple times for each list element while
key
and
reverse
touch each element only once. Use
functools.cmp_to_key()
以转换旧样式
cmp
函数到
key
函数。
内置
sorted()
函数保证是稳定的。排序是稳定的,若保证不改变比较相等元素的相对次序 — 这有助于多遍排序 (例如:按部门排序,然后按薪金等级排序)。
对于排序范例和简短排序教程,见 排序怎么样 .
2.4 版新增。
staticmethod
(
function
)
¶
返回静态方法为 function .
静态方法不接收第 1 隐含自变量。要声明静态方法,使用此习语:
class C(object): @staticmethod def f(arg1, arg2, ...): ...
The
@staticmethod
形式是函数
装饰器
– 见
函数定义
了解细节。
可以调用静态方法在类 (譬如
C.f()
) 或在实例 (譬如
C().f()
).
Python 静态方法类似 Java 或 C++ 中找到的那些。另请参阅
classmethod()
了解创建替代类构造函数的有用变体。
有关静态方法的更多信息,见 标准类型层次结构 .
2.2 版新增。
2.4 版改变: 添加函数装饰器句法。
str
(
object=''
)
¶
Return a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with
repr(object)
is that
str(object)
does not always attempt to return a string that is acceptable to
eval()
; its goal is to return a printable string. If no argument is given, returns the empty string,
''
.
For more information on strings see
Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange
which describes sequence functionality (strings are sequences), and also the string-specific methods described in the
字符串方法
section. To output formatted strings use template strings or the
%
operator described in the
字符串格式化操作
section. In addition see the
String Services
章节。另请参阅
unicode()
.
sum
(
iterable
[
,
start
]
)
¶
求和
start
和项对于
iterable
从左到右并返回总数。
start
默认为
0
。
iterable
的项通常是数字,且 start 值不允许是字符串。
对于某些用例,有很好的替代对于
sum()
。串联字符串序列的快速首选方式,是调用
''.join(sequence)
。要相加具有扩展精度的浮点值,见
math.fsum()
。为串联一系列可迭代,考虑使用
itertools.chain()
.
2.3 版新增。
super
(
type
[
,
object-or-type
]
)
¶
返回的代理对象将方法调用委托给父级或同级类的
type
. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by
getattr()
except that the
type
itself is skipped.
The
__mro__
属性在
type
lists the method resolution search order used by both
getattr()
and
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)
必须为 True (这对类方法很有用)。
注意
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).
对于这 2 用例,典型超类调用看起来像这样:
class C(B): def method(self, arg): super(C, self).method(arg)
注意,
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__()
method for searching classes in a predictable order that supports cooperative multiple inheritance. Accordingly,
super()
is undefined for implicit lookups using statements or operators such as
super()[name]
.
另请注意
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() 使用指南
.
2.2 版新增。
tuple
(
[
iterable
]
)
¶
Return a tuple whose items are the same and in the same order as
iterable
’s items.
iterable
may be a sequence, a container that supports iteration, or an iterator object. If
iterable
is already a tuple, it is returned unchanged. For instance,
tuple('abc')
返回
('a', 'b', 'c')
and
tuple([1, 2,
3])
返回
(1, 2, 3)
. If no argument is given, returns a new empty tuple,
()
.
tuple
is an immutable sequence type, as documented in
Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange
. For other containers see the built in
dict
,
list
,和
set
类,和
collections
模块。
type
(
对象
)
¶
type
(
名称
,
bases
,
dict
)
采用 1 自变量,返回类型为
object
. The return value is a type object. The
isinstance()
built-in function is recommended for testing the type of an object.
采用 3 自变量,返回新类型对象。这本质上是动态形式的
class
语句。
name
字符串是类名并变为
__name__
属性;
bases
tuple itemizes the base classes and becomes the
__bases__
attribute; and the
dict
dictionary is the namespace containing definitions for class body and becomes the
__dict__
attribute. For example, the following two statements create identical
type
对象:
>>> class X(object):
... a = 1
...
>>> X = type('X', (object,), dict(a=1))
2.2 版新增。
unichr
(
i
)
¶
Return the Unicode string of one character whose Unicode code is the integer
i
。例如,
unichr(97)
返回字符串
u'a'
。这是逆
ord()
for Unicode strings. The valid range for the argument depends how Python was configured – it may be either UCS2 [0..0xFFFF] or UCS4 [0..0x10FFFF].
ValueError
is raised otherwise. For ASCII and 8-bit strings see
chr()
.
2.0 版新增。
unicode
(
object=''
)
¶
unicode
(
对象
[
,
encoding
[
,
errors
]
]
)
Return the Unicode string version of object using one of the following modes:
若
encoding
and/or
errors
的给定,
unicode()
will decode the object which can either be an 8-bit string or a character buffer using the codec for
encoding
。
encoding
parameter is a string giving the name of an encoding; if the encoding is not known,
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'
(默认),
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
模块。
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__()
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'
模式。
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
字符串方法
section. To output formatted strings use template strings or the
%
operator described in the
字符串格式化操作
section. In addition see the
String Services
章节。另请参阅
str()
.
2.0 版新增。
2.2 版改变:
支持
__unicode__()
added.
vars
(
[
对象
]
)
¶
返回
__dict__
属性对于模块、类、实例或任何其它对象具有
__dict__
属性。
对象譬如模块和实例拥有可更新
__dict__
属性;不管怎样,其它对象可以拥有写入限定在它们的
__dict__
attributes (for example, new-style classes use a dictproxy to prevent direct dictionary updates).
没有自变量,
vars()
举动像
locals()
. Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.
xrange
(
stop
)
¶
xrange
(
start
,
stop
[
,
step
]
)
This function is very similar to
range()
, but returns an
xrange object
instead of a list. This is an opaque sequence type which yields the same values as the corresponding list, without actually storing them all simultaneously. The advantage of
xrange()
over
range()
is minimal (since
xrange()
still has to create the values when asked for them) except when a very large range is used on a memory-starved machine or when all of the range’s elements are never used (such as when the loop is usually terminated with
break
). For more information on xrange objects, see
XRange Type
and
Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange
.
CPython 实现细节:
xrange()
is intended to be simple and fast. Implementations may impose restrictions to achieve this. The C implementation of Python restricts all arguments to native C longs (“short” Python integers), and also requires that the number of elements fit in a native C long. If a larger range is needed, an alternate version can be crafted using the
itertools
模块:
islice(count(start, step),
(stop-start+step-1+2*(step<0))//step)
.
zip
(
[
iterable
,
...
]
)
¶
This function returns a list of tuples, where the
i
-th tuple contains the
i
-th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence. When there are multiple arguments which are all of the same length,
zip()
类似于
map()
with an initial argument of
None
. With a single sequence argument, it returns a list of 1-tuples. With no arguments, it returns an empty list.
The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using
zip(*[iter(s)]*n)
.
zip()
in conjunction with the
*
operator can be used to unzip a list:
>>> 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 版改变:
Formerly,
zip()
required at least one argument and
zip()
raised a
TypeError
instead of returning an empty list.
__import__
(
名称
[
,
globals
[
,
locals
[
,
fromlist
[
,
level
]
]
]
]
)
¶
注意
这是日常 Python 编程不需要的高级函数,不像
importlib.import_module()
.
此函数的援引是通过
import
语句。它可以被替换 (通过导入
__builtin__
模块并赋值
__builtin__.__import__
) 以改变语义对于
import
statement, but nowadays it is usually simpler to use import hooks (see
PEP 302
). Direct use of
__import__()
is rare, except in cases where you want to import a module whose name is only known at runtime.
函数导入模块
name
,潜在使用给定
globals
and
locals
以确定如何解释包上下文中的名称。
fromlist
给出应导入对象 (或子模块) 的名称从给定模块按
name
。标准实现不使用其
locals
自变量根本,而是使用其
globals
仅以确定包上下文为
import
语句。
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
指示相对于模块目录要搜索的父级目录数调用
__import__()
.
当
name
变量的形式为
package.module
,通常,返回顶层包 (第一点之后的名称),
not
模块命名通过
name
。不管怎样,当非空
fromlist
自变量有给定,模块命名通过
name
被返回。
例如,语句
import spam
产生类似以下代码的字节码:
spam = __import__('spam', globals(), locals(), [], -1)
语句
import spam.ham
产生此调用:
spam = __import__('spam.ham', globals(), locals(), [], -1)
注意如何
__import__()
在此返回顶层模块,因为这是被绑定到名称的对象通过
import
语句。
另一方面,语句
from spam.ham import eggs, sausage as
saus
产生
_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], -1) eggs = _temp.eggs saus = _temp.sausage
在这里,
spam.ham
模块的返回来自
__import__()
。从此对象,检索要导入的名称并分别赋值名称。
若只想按名称导入模块 (可能在包中),使用
importlib.import_module()
.
Changed in version 2.5: The level parameter was added.
Changed in version 2.5: Keyword support for parameters was added.
There are several built-in functions that are no longer essential to learn, know or use in modern Python programming. They have been kept here to maintain backwards compatibility with programs written for older versions of Python.
Python programmers, trainers, students and book writers should feel free to bypass these functions without concerns about missing something important.
apply
(
function
,
args
[
,
keywords
]
)
¶
The
function
argument must be a callable object (a user-defined or built-in function or method, or a class object) and the
args
argument must be a sequence. The
function
is called with
args
as the argument list; the number of arguments is the length of the tuple. If the optional
keywords
argument is present, it must be a dictionary whose keys are strings. It specifies keyword arguments to be added to the end of the argument list. Calling
apply()
is different from just calling
function(args)
, since in that case there is always exactly one argument. The use of
apply()
相当于
function(*args, **keywords)
.
从 2.3 版起弃用:
使用
function(*args, **keywords)
而不是
apply(function, args, keywords)
(见
解包自变量列表
).
buffer
(
对象
[
,
offset
[
,
size
]
]
)
¶
The object argument must be an object that supports the buffer call interface (such as strings, arrays, and buffers). A new buffer object will be created which references the object argument. The buffer object will be a slice from the beginning of object (or from the specified offset ). The slice will extend to the end of object (or will have a length given by the size argument).
coerce
(
x
,
y
)
¶
Return a tuple consisting of the two numeric arguments converted to a common type, using the same rules as used by arithmetic operations. If coercion is not possible, raise
TypeError
.
intern
(
string
)
¶
Enter string in the table of “interned” strings and return the interned string – which is string itself or a copy. Interning strings is useful to gain a little performance on dictionary lookup – if the keys in a dictionary are interned, and the lookup key is interned, the key comparisons (after hashing) can be done by a pointer compare instead of a string compare. Normally, the names used in Python programs are automatically interned, and the dictionaries used to hold module, class or instance attributes have interned keys.
Changed in version 2.3:
Interned strings are not immortal (like they used to be in Python 2.2 and before); you must keep a reference to the return value of
intern()
around to benefit from it.
脚注
It is used relatively rarely so does not warrant being made into a statement.
Specifying a buffer size currently has no effect on systems that don’t have
setvbuf()
. The interface to specify the buffer size is not done using a method that calls
setvbuf()
, because that may dump core when called after any I/O has been performed, and there’s no reliable way to determine whether this is the case.
In the current implementation, local variable bindings cannot normally be affected this way, but variables retrieved from other scopes (such as modules) can be. This may change.