本文摘自:https://docs.python.org/3/library/functions.html?highlight=built#ascii
内置功能 | ||||
---|---|---|---|---|
|
-
abs
(x ) 返回数字的绝对值。参数可以是整数或浮点数。如果参数是一个复数,则返回其大小。
-
all
(可迭代的) 返回
True
如果的所有元素迭代是真实的(或者如果可迭代为空)。相当于:def all(iterable): for element in iterable: if not element: return False return True
-
any
(可迭代的) True
如果iterable的任何元素为true ,则返回。如果iterable为空,则返回False
。相当于:def any(iterable): for element in iterable: if element: return True return False
-
ascii
(对象) 如
repr()
,由返回的字符串中返回一个包含对象的可打印表示一个字符串,但逃避非ASCII字符repr()
使用\x
,\u
或\U
逃逸。这会生成一个类似于repr()
Python 2 中返回的字符串。
-
bin
(x ) 将整数转换为前缀为“0b”的二进制字符串。结果是一个有效的Python表达式。如果x不是Python
int
对象,则必须定义一个__index__()
返回整数的方法。一些例子:>>> bin(3) '0b11' >>> bin(-10) '-0b1010'
如果需要前缀“0b”,您可以使用以下任一方法。
>>> format(14, '#b'), format(14, 'b') ('0b1110', '1110') >>> f'{14:#b}', f'{14:b}' ('0b1110', '1110')
另请参阅
format()
以获取更多信息。
- class
bool
([ x ] ) 返回一个布尔值,即
True
或者之一False
。 使用标准真值测试程序转换x。如果x为false或省略,则返回; 否则它会返回。的 类是的子类(参见数值类型-整数,浮点,复合)。它不能进一步细分。它的唯一实例是和 (参见布尔值)。False
True
bool
int
False
True
在版本3.7中更改:x现在是仅位置参数。
-
breakpoint
(* args,** kws ) 此函数会将您置于调用站点的调试器中。具体来说,它呼叫
sys.breakpointhook()
,传递args
和kws
直接通过。默认情况下,sys.breakpointhook()
调用pdb.set_trace()
不需要参数。在这种情况下,它纯粹是一个便利功能,因此您不必显式导入pdb
或输入尽可能多的代码来进入调试器。但是,sys.breakpointhook()
可以设置为其他一些功能并breakpoint()
自动调用它,允许您进入选择的调试器。版本3.7中的新功能。
- class
bytearray
([ source [,encoding [,errors ] ] ] ) 返回一个新的字节数组。的
bytearray
类是整数的范围为0 <= X一个可变的序列<256它具有最的可变序列,在所描述的常规方法的可变序列类型,以及大多数方法,该bytes
类型已见字节和ByteArray操作。可选的source参数可用于以几种不同的方式初始化数组:
如果它是一个字符串,您还必须提供编码(和可选的, 错误)参数;
bytearray()
然后使用将字符串转换为字节str.encode()
。如果它是一个整数,则该数组将具有该大小,并将使用空字节进行初始化。
如果它是符合缓冲区接口的对象,则将使用该对象的只读缓冲区来初始化bytes数组。
如果它是可迭代的,则它必须是范围内的可迭代整数 ,它们用作数组的初始内容。
0 <= x < 256
如果没有参数,则会创建一个大小为0的数组。
- class
bytes
([ source [,encoding [,errors ] ] ] ) 返回一个新的“bytes”对象,该对象是该范围内不可变的整数序列。 是一个不可变的版本 – 它具有相同的非变异方法和相同的索引和切片行为。
0 <= x < 256
bytes
bytearray
因此,构造函数参数被解释为
bytearray()
。也可以使用文字创建字节对象,请参阅字符串和字节文字。
另请参见二进制序列类型 – 字节,字节数组,内存视图,字节对象以及字节和字节操作。
-
callable
(对象) True
如果object参数显示为可调用False
则返回,否则返回。如果返回true,则调用仍然可能失败,但如果调用失败,则调用对象将永远不会成功。请注意,类是可调用的(调用类会返回一个新实例); 如果实例的类具有__call__()
方法,则它们是可调用的。版本3.2中的新功能:此功能首先在Python 3.0中删除,然后在Python 3.2中恢复。
-
chr
(i ) 返回表示Unicode代码点为整数i的字符的字符串。例如,
chr(97)
返回字符串'a'
,同时chr(8364)
返回字符串'€'
。这是相反的ord()
。参数的有效范围是0到1,114,111(基数为16的0x10FFFF)。
ValueError
如果我超出该范围,我将被提出。
-
@
classmethod
将方法转换为类方法。
类方法接收类作为隐式的第一个参数,就像实例方法接收实例一样。要声明一个类方法,请使用此成语:
class C: @classmethod def f(cls, arg1, arg2, ...): ...
该
@classmethod
形式是一个函数装饰 -见 函数定义的详细信息。可以在类(例如
C.f()
)或实例(例如C().f()
)上调用类方法。除了类之外,该实例被忽略。如果为派生类调用类方法,则派生类对象将作为隐含的第一个参数传递。类方法与C ++或Java静态方法不同。如果你想要那些,请参阅
staticmethod()
。有关类方法的更多信息,请参阅标准类型层次结构。
-
compile
(source,filename,mode,flags = 0,dont_inherit = False,optimize = -1 ) 将源代码编译为代码或AST对象。代码对象可以由
exec()
或执行eval()
。 source可以是普通字符串,字节字符串或AST对象。ast
有关如何使用AST对象的信息,请参阅模块文档。该文件名参数应该给从代码读取的文件; 如果没有从文件中读取(
'<string>'
通常使用),则传递一些可识别的值。该模式参数指定什么样的代码必须进行编译; 它可以是
'exec'
,如果源包含的语句序列的,'eval'
如果它由一个单一的表达的,或者'single'
如果它由单个交互式声明的(在后一种情况下,计算结果为比其他东西表达式语句None
将被打印)。可选参数flags和dont_inherit控制将来的语句影响源的编译。如果两者都不存在(或两者都为零),则使用在调用的代码中生效的未来语句编译代码
compile()
。如果 给出flags参数且dont_inherit不是(或为零),那么除了将要使用的那些之外,还使用flags参数指定的future语句。如果dont_inherit是一个非零整数,那么flags参数就是它 – 忽略了对编译调用有效的未来语句。将来的语句由位指定,这些位可以按位OR运算以指定多个语句。指定给定特征所需的位域可以作为模块中实例的
compiler_flag
属性找到。_Feature
__future__
参数optimize指定编译器的优化级别; 默认值
-1
选择由-O
选项给出的解释器的优化级别。显式级别是0
(没有优化;__debug__
是真的),1
(断言被删除,__debug__
是假的)或2
(文档字符串也被删除)。SyntaxError
如果编译的源无效,并且ValueError
源包含空字节,则此函数引发。如果要将Python代码解析为其AST表示,请参阅
ast.parse()
。注意
在
'single'
或'eval'
模式下使用多行代码编译字符串时,输入必须至少由一个换行符终止。这有助于检测code
模块中不完整和完整的语句。警告
由于Python AST编译器中的堆栈深度限制,在编译为AST对象时,可能会使Python解释器崩溃并使用足够大/复杂的字符串。
版本3.2中已更改:允许使用Windows和Mac换行符。在
'exec'
模式下输入也不必再以换行符结束。添加了optimize参数。在版本3.5中更改:以前
TypeError
在源中遇到空字节时引发。
- class
complex
([ real [,imag ] ] ) 返回值为real + imag * 1j的复数或将字符串或数字转换为复数。如果第一个参数是一个字符串,它将被解释为一个复数,并且必须在没有第二个参数的情况下调用该函数。第二个参数永远不能是字符串。每个参数可以是任何数字类型(包括复数)。如果IMAG被省略,默认为零,并且构造用作数字转换等
int
和float
。如果省略两个参数,则返回0j
。注意
从字符串转换时,字符串不得包含中心
+
或-
运算符周围的空格。例如,complex('1+2j')
很好,但提高 。complex('1 + 2j')
ValueError
复杂类型在Numeric Types中描述– int,float,complex。
在版本3.6中更改:允许使用下划线对数字进行分组,如代码文字中所示。
-
delattr
(对象,名称) 这是一个亲戚
setattr()
。参数是一个对象和一个字符串。该字符串必须是对象属性之一的名称。如果对象允许,该函数将删除命名属性。例如,相当于。delattr(x, 'foobar')
del x.foobar
- 上课
dict
(** kwarg ) - class
dict
(mapping,** kwarg ) - class
dict
(iterable,** kwarg ) 创建一个新的字典。该
dict
对象是字典类。有关此类的文档,请参阅dict
和映射类型 – dict。对于其他容器,请参阅内置的 in
list
,set
和tuple
类以及collections
模块。
-
dir
([ 对象] ) 如果没有参数,则返回当前本地范围中的名称列表。使用参数,尝试返回该对象的有效属性列表。
如果对象具有名为的
__dir__()
方法,则将调用此方法,并且必须返回属性列表。这允许实现自定义__getattr__()
或__getattribute__()
函数的对象自 定义dir()
报告其属性的方式 。如果对象未提供
__dir__()
,则该函数会尽力从对象的__dict__
属性(如果已定义)和其类型对象中收集信息。结果列表不一定完整,并且在对象具有自定义时可能不准确__getattr__()
。默认
dir()
机制对不同类型的对象表现不同,因为它尝试生成最相关但非完整的信息:如果对象是模块对象,则列表包含模块属性的名称。
如果对象是类型或类对象,则列表包含其属性的名称,并且递归地包含其基础的属性。
否则,该列表包含对象的属性名称,其类的属性的名称,以及其类的基类的属性的递归。
结果列表按字母顺序排序。例如:
>>> import struct >>> dir() # show the names in the module namespace # doctest: +SKIP ['__builtins__', '__name__', 'struct'] >>> dir(struct) # show the names in the struct module # doctest: +SKIP ['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__initializing__', '__loader__', '__name__', '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into', 'unpack', 'unpack_from'] >>> class Shape: ... def __dir__(self): ... return ['area', 'perimeter', 'location'] >>> s = Shape() >>> dir(s) ['area', 'location', 'perimeter']
注意
因为
dir()
它主要是为了方便在交互式提示中使用而提供的,所以它试图提供一组有趣的名称,而不是尝试提供严格或一致定义的名称集,并且其详细行为可能会在不同版本之间发生变化。例如,当参数是类时,元类属性不在结果列表中。
-
divmod
(a,b ) 取两个(非复数)数作为参数,并在使用整数除法时返回由商和余数组成的一对数字。对于混合操作数类型,二进制算术运算符的规则适用。对于整数,结果与之相同。对于浮点数,结果是,其中q通常但可能比该值小1。在任何情况下非常接近a,如果非零,则它与b具有相同的符号,并且。
(a // b, a % b)
(q, a %b)
math.floor(a / b)
q * b + a % b
a % b
0 <= abs(a % b) < abs(b)
-
enumerate
(iterable,start = 0 ) 返回一个枚举对象。iterable必须是一个序列,一个 迭代器或一些支持迭代的对象。
__next__()
返回的迭代器的方法enumerate()
返回一个包含计数的元组(从start开始,默认为0)和迭代迭代得到的值。>>> 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
-
eval
(表达式,globals = None,locals = None ) 参数是一个字符串和可选的全局变量和本地变量。如果提供, globals必须是字典。如果提供,则locals可以是任何映射对象。
该表达参数分析,并作为一个Python表达式来使用(从技术上来说,一个条件列表)全局和当地人 的字典作为全局和局部名字空间。如果全局字典存在且不包含键的值,则在解析表达式之前,将在该键下插入对内置模块的字典的引用。这意味着表达式通常具有对标准模块的完全访问权限,并且传播受限制的环境。如果省略locals字典,则默认为globals
__builtins__
builtins
builtins
字典。如果省略两个字典,则表达式在eval()
调用的环境中执行。返回值是计算表达式的结果。语法错误报告为异常。例:>>> x = 1 >>> eval('x+1') 2
此函数还可用于执行任意代码对象(例如由其创建的代码对象
compile()
)。在这种情况下,传递代码对象而不是字符串。如果代码对象已经被编译'exec'
为 模式的说法,eval()
“返回值会None
。提示:
exec()
函数支持动态执行语句。的globals()
和locals()
功能返回当前全球和本地词典,分别,其可以是通过以绕过使用有用eval()
或exec()
。请参阅
ast.literal_eval()
可以安全地使用仅包含文字的表达式来评估字符串的函数。
-
exec
(object [,globals [,locals ] ] ) 此函数支持Python代码的动态执行。object必须是字符串或代码对象。如果它是一个字符串,则将该字符串解析为一组Python语句,然后执行该语句(除非发生语法错误)。1如果它是代码对象,则只执行它。在所有情况下,执行的代码应该作为文件输入有效(请参见“参考手册”中的“文件输入”部分)。请注意, 即使在传递给函数的代码的上下文中,也不能在函数定义之外使用
return
和yield
语句exec()
。返回值是None
。在所有情况下,如果省略可选部分,则代码在当前范围内执行。如果只提供全局变量,则它必须是字典,它将用于全局变量和局部变量。如果全局和 当地人给出,它们分别用于全局和局部变量。如果提供,则locals可以是任何映射对象。请记住,在模块级别,全局变量和本地变量是相同的字典。如果exec获得两个单独的对象作为全局变量和局部变量,则代码将被执行,就像它嵌入在类定义中一样。
如果全局字典不包含键的值, 则在该键下插入对内置模块 的字典的引用。这样,您可以通过在传递给自己的字典之前将自己的字典插入到全局变量中来控制已执行代码可用的 内置函数 。
__builtins__
builtins
__builtins__
exec()
注意
在建 -in功能
globals()
和locals()
返回当前的全局和局部字典,分别,这可能是传递用作第二个和第三个参数有用exec()
。注意
默认的locals如
locals()
下面的函数所述:不应尝试修改默认的locals字典。如果需要在函数返回后查看本地代码的效果,则传递显式的本地字典。exec()
-
filter
(功能,可迭代) 从iterable的那些元素构造一个迭代器,函数 返回true。 iterable可以是序列,支持迭代的容器,也可以是迭代器。如果功能是
None
,同样的函数被假定,那就是,所有的元素迭代是假的被删除。注意,如果函数不是,如果函数是 ,则等效于生成器表达式。
filter(function, iterable)
(item for itemin iterable if function(item))
None
(item for item in iterable if item)
None
请参阅
itertools.filterfalse()
补充函数,该函数返回iterable的元素,该函数返回false。
- class
float
([ x ] ) 返回由数字或字符串x构造的浮点数。
如果参数是一个字符串,它应该包含一个十进制数字,可选地以符号开头,并且可选地嵌入在空格中。可选标志可以是
'+'
或'-'
; 一个'+'
符号具有上产生的值没有影响。参数也可以是表示NaN(非数字)或正或负无穷大的字符串。更确切地说,在删除前导和尾随空格字符后,输入必须符合以下语法:sign :: =“+”| “ - ” infinity :: =“Infinity”| “inf” nan :: =“nan” numeric_value :: =
floatnumber
|infinity
| numeric_string :: = [ ]nan
sign
numeric_value
下面
floatnumber
是浮点文字中描述的Python浮点文字的形式。案例并不重要,因此,例如,“inf”,“Inf”,“INFINITY”和“iNfINity”都是正无限的可接受拼写。否则,如果参数是整数或浮点数,则返回具有相同值的浮点数(在Python的浮点精度内)。如果参数超出了Python float的范围,
OverflowError
则会引发一个。对于一般Python对象
x
,float(x)
委托给x.__float__()
。如果没有给出参数,
0.0
则返回。例子:
>>>
>>> float('+1.23') 1.23 >>> float(' -12345\n') -12345.0 >>> float('1e-003') 0.001 >>> float('+1E6') 1000000.0 >>> float('-Infinity') -inf
float类型在Numeric Types中描述– int,float,complex。
在版本3.6中更改:允许使用下划线对数字进行分组,如代码文字中所示。
在版本3.7中更改:x现在是仅位置参数。
-
format
(value [,format_spec ] ) 将值转换为“格式化”表示,由format_spec控制 。format_spec的解释将取决于value参数的类型,但是大多数内置类型都使用标准格式化语法:Format Specification Mini-Language。
默认的format_spec是一个空字符串,通常与调用具有相同的效果
str(value)
。转换为 在搜索值的方法时绕过实例字典的调用。一 ,如果该方法搜索到达引发异常 和format_spec非空,或者这两个 format_spec或返回值是不是字符串。
format(value,format_spec)
type(value).__format__(value, format_spec)
__format__()
TypeError
object
在版本3.4中更改: 如果format_spec不是空字符串,则
object().__format__(format_spec)
引发。TypeError
- class
frozenset
([ iterable ] ) 返回一个新
frozenset
对象,可选地包含从iterable中获取的元素 。frozenset
是一个内置的类。有关此类的文档,请参阅frozenset
和 设置类型 – set,frozenset。对于其他容器看到内置 -in
set
,list
,tuple
,和dict
类,还有collections
模块。
-
getattr
(对象,名称[,默认] ) 返回object的named属性的值。 name必须是一个字符串。如果字符串是对象属性之一的名称,则结果是该属性的值。例如,相当于 。如果named属性不存在,则返回default(如果提供),否则引发。
getattr(x,'foobar')
x.foobar
AttributeError
-
globals
() 返回表示当前全局符号表的字典。这始终是当前模块的字典(在函数或方法内部,这是定义它的模块,而不是调用它的模块)。
-
hasattr
(对象,名称) 参数是一个对象和一个字符串。结果是,
True
如果字符串是对象属性之一的名称,False
如果不是。(这是通过调用并查看它是否会引发来实现的。)getattr(object, name)
AttributeError
-
hash
(对象) 返回对象的哈希值(如果有的话)。哈希值是整数。它们用于在字典查找期间快速比较字典键。比较相等的数字值具有相同的哈希值(即使它们具有不同的类型,如1和1.0的情况)。
注意
对于具有自定义
__hash__()
方法的对象,请注意hash()
根据主机的位宽截断返回值。详情__hash__()
请见。
-
help
([ 对象] ) 调用内置的帮助系统。(此函数用于交互式使用。)如果未给出参数,则交互式帮助系统将在解释器控制台上启动。如果参数是字符串,则查找字符串作为模块,函数,类,方法,关键字或文档主题的名称,并在控制台上打印帮助页面。如果参数是任何其他类型的对象,则会生成对象的帮助页面。
请注意,如果函数的参数列表中出现斜杠(/),则在调用时
help()
,意味着斜杠之前的参数仅为位置参数。有关详细信息,请参阅 有关仅位置参数的FAQ条目。此函数由模块添加到内置命名空间
site
。
-
hex
(x ) 将整数转换为带有前缀“0x”的小写十六进制字符串。如果x不是Python
int
对象,则必须定义一个__index__()
返回整数的 方法。一些例子:>>> hex(255) '0xff' >>> hex(-42) '-0x2a'
如果要将整数转换为带有前缀或不带前缀的大写或小写十六进制字符串,可以使用以下任一方法:
>>> '%#x' % 255, '%x' % 255, '%X' % 255 ('0xff', 'ff', 'FF') >>> format(255, '#x'), format(255, 'x'), format(255, 'X') ('0xff', 'ff', 'FF') >>> f'{255:#x}', f'{255:x}', f'{255:X}' ('0xff', 'ff', 'FF')
另请参阅
format()
以获取更多信息。另请参阅
int()
使用16的基数将十六进制字符串转换为整数。注意
要获取float的十六进制字符串表示形式,请使用该
float.hex()
方法。
-
id
(对象) 返回对象的“标识”。这是一个整数,在该生命周期内保证该对象是唯一且恒定的。具有非重叠寿命的两个对象可以具有相同的
id()
值。CPython实现细节:这是内存中对象的地址。
-
input
([ 提示] ) 如果存在prompt参数,则将其写入标准输出而不带尾随换行符。然后,该函数从输入中读取一行,将其转换为字符串(剥离尾部换行符),然后返回该行。读取EOF时,
EOFError
会引发。例:>>>
>>> s = input('--> ') --> Monty Python's Flying Circus >>> s "Monty Python's Flying Circus"
- class
int
([ x ] ) - class
int
(x,base = 10 ) 返回由数字或字符串x构造的整数对象,
0
如果没有给出参数,则返回 。如果x定义__int__()
,则int(x)
返回x.__int__()
。如果x定义__trunc__()
,则返回x.__trunc__()
。对于浮点数,这会截断为零。如果X不是数字或如果基给出,则X必须是一个字符串,
bytes
或bytearray
代表一个实例字面整数在基数基。可选地,文字可以在+
或之前-
(之间没有空格)并且由空格包围。base-n文字由数字0到n-1组成,a
toz
(或A
toZ
)的值为10到35.默认基数为10.允许的值为0和2-36。Base-2,-8和-16文字可以选择以0b
/0B
,0o
/0O
或0x
/ 为前缀0X
,与代码中的整数文字一样。基数0表示完全解释为代码文字,因此实际基数为2,8,10或16,因此这是不合法的,同时 也是。int('010', 0)
int('010')
int('010', 8)
整数类型在数值类型中描述– int,float,complex。
在版本3.4中更改:如果base不是实例,
int
并且基础对象具有base.__index__
方法,则调用该方法以获取基础的整数。以前的版本使用base.__int__
而不是base.__index__
。在版本3.6中更改:允许使用下划线对数字进行分组,如代码文字中所示。
在版本3.7中更改:x现在是仅位置参数。
-
isinstance
(对象,classinfo ) 如果object参数是classinfo 参数的实例,或者是(直接,间接或虚拟)子类的实例,则返回true 。如果object不是给定类型的对象,则该函数始终返回false。如果classinfo是类型对象的元组(或递归,其他此类元组),如果object是任何类型的实例,则返回true 。如果classinfo不是类型和类型元组的类型或元组,
TypeError
则会引发异常。
-
issubclass
(class,classinfo ) 如果class是classinfo的子类(直接,间接或虚拟),则返回true 。类被认为是其自身的子类。classinfo可以是类对象的元组,在这种情况下,将检查classinfo中的每个条目。在任何其他情况下,都会引发异常。
TypeError
-
iter
(对象[,sentinel ] ) 返回一个迭代器对象。根据第二个参数的存在,第一个参数的解释非常不同。如果没有第二个参数,对象必须是支持迭代协议(
__iter__()
方法)的集合对象,或者它必须支持序列协议(从__getitem__()
整数参数开始的方法0
)。如果它不支持这些协议中的任何一个,TypeError
则引发。如果给出第二个参数sentinel,则object必须是可调用对象。在这种情况下创建的迭代器将为每个对其方法的调用调用没有参数的 对象__next__()
; 如果返回的值等于 sentinel,StopIteration
将被提出,否则将返回该值。另请参见迭代器类型。
第二种形式的一个有用的应用
iter()
是构建块读取器。例如,从二进制数据库文件中读取固定宽度的块,直到达到文件末尾:from functools import partial with open('mydata.db', 'rb') as f: for block in iter(partial(f.read, 64), b''): process_block(block)
-
len
(s ) 返回对象的长度(项目数)。参数可以是序列(例如字符串,字节,元组,列表或范围)或集合(例如字典,集合或冻结集)。
- class
list
([ iterable ] ) 实际上,它不是一个函数,而是
list
一个可变序列类型,如列表和序列类型中所述 – 列表,元组,范围。
-
locals
() 更新并返回表示当前本地符号表的字典。自由变量
locals()
在函数块中调用时返回,但不在类块中调用。请注意,在模块级别,locals()
并且globals()
是相同的字典。注意
不应修改此词典的内容; 更改可能不会影响解释器使用的本地和自由变量的值。
-
map
(功能,可迭代,…… ) 返回一个迭代器,它将函数应用于每个iterable项,从而产生结果。如果传递了其他可迭代参数,则 函数必须采用那么多参数,并且并行地应用于所有迭代的项。对于多个迭代,迭代器在最短的iterable耗尽时停止。对于函数输入已经安排到参数元组的情况,请参阅
itertools.starmap()
。
-
max
(iterable,* [,key,default ] ) -
max
(arg1,arg2,* args [,key ] ) 返回可迭代中的最大项或两个或多个参数中的最大项。
如果提供了一个位置参数,则它应该是可迭代的。返回iterable中的最大项。如果提供了两个或多个位置参数,则返回最大的位置参数。
有两个可选的仅关键字参数。该关键参数指定一个参数的排序功能,类似于用于
list.sort()
。该 默认参数指定的对象返回如果提供的迭代是空的。如果iterable为空并且未提供default,ValueError
则引发a。如果多个项目是最大的,则该函数返回遇到的第一个项目。这与其他排序稳定性保留工具(例如和)一致 。
sorted(iterable, key=keyfunc, reverse=True)[0]
heapq.nlargest(1, iterable, key=keyfunc)
在新版本3.4:在默认情况下只有关键字的说法。
-
memoryview
(obj ) 返回从给定参数创建的“内存视图”对象。有关更多信息,请参阅 内存视图
-
min
(iterable,* [,key,default ] ) -
min
(arg1,arg2,* args [,key ] ) 返回可迭代中的最小项或两个或多个参数中的最小项。
如果提供了一个位置参数,则它应该是可迭代的。返回iterable中的最小项。如果提供了两个或多个位置参数,则返回最小的位置参数。
有两个可选的仅关键字参数。该关键参数指定一个参数的排序功能,类似于用于
list.sort()
。该 默认参数指定的对象返回如果提供的迭代是空的。如果iterable为空并且未提供default,ValueError
则引发a。如果多个项目是最小的,则该函数返回遇到的第一个项目。这与其他排序稳定性保留工具(例如和)一致。
sorted(iterable, key=keyfunc)[0]
heapq.nsmallest(1, iterable, key=keyfunc)
在新版本3.4:在默认情况下只有关键字的说法。
-
next
(迭代器[,默认] ) 通过调用其 方法从迭代器中检索下一个项目
__next__()
。如果给定default,则在迭代器耗尽时返回,否则StopIteration
引发。
- 类
object
返回一个新的无特征对象。
object
是所有课程的基础。它具有所有Python类实例共有的方法。此函数不接受任何参数。注意
-
oct
(x ) 将整数转换为前缀为“0o”的八进制字符串。结果是一个有效的Python表达式。如果x不是Python
int
对象,则必须定义一个__index__()
返回整数的方法。例如:>>> oct(8) '0o10' >>> oct(-56) '-0o70'
如果要将整数转换为带有前缀“0o”的八进制字符串,可以使用以下任一方法。
>>> '%#o' % 10, '%o' % 10 ('0o12', '12') >>> format(10, '#o'), format(10, 'o') ('0o12', '12') >>> f'{10:#o}', f'{10:o}' ('0o12', '12')
另请参阅
format()
以获取更多信息。
-
open
(file,mode =’r’,buffering = -1,encoding = None,errors = None,newline = None,closefd = True,opener = None ) 打开文件并返回相应的文件对象。如果无法打开文件,
OSError
则引发a。file是一个类似路径的对象,给出要打开的文件的路径名(绝对或相对于当前工作目录)或要包装的文件的整数文件描述符。(如果给出了文件描述符,则在关闭返回的I / O对象时关闭它,除非将closefd 设置为
False
。)mode是一个可选字符串,用于指定打开文件的模式。它默认
'r'
为在文本模式下打开以进行读取。其他常见值'w'
用于写入(如果文件已存在则截断文件),'x'
独占创建和'a'
附加(在某些 Unix系统上,意味着所有写入都附加到文件末尾而不管当前搜索位置)。在文本模式下,如果 编码未指定使用的编码是与平台相关的:locale.getpreferredencoding(False)
被称为获取当前的本地编码。(对于读取和写入原始字节,请使用二进制模式并保留 编码未指定。)可用模式为:字符
含义
'r'
开放阅读(默认)
'w'
打开写入,先截断文件
'x'
打开以进行独占创建,如果文件已存在则失败
'a'
打开以进行写入,如果存在则附加到文件的末尾
'b'
二进制模式
't'
文字模式(默认)
'+'
打开磁盘文件进行更新(读写)
默认模式是
'r'
(打开以读取文本,同义词'rt'
)。对于二进制读写访问,模式'w+b'
打开并将文件截断为0字节。'r+b'
打开文件而不截断。如概述中所述,Python区分二进制和文本I / O. 以二进制模式打开的文件(包括
'b'
在mode 参数中)将内容作为bytes
对象返回,而不进行任何解码。在文本模式(默认情况下,或者't'
包含在mode参数中)时,文件的内容将返回为str
,首先使用平台相关编码或使用指定的编码(如果给定)对字节进行解码 。允许使用其他模式字符
'U'
,该字符不再具有任何效果,并且被视为已弃用。它以前在文本模式下启用了 通用换行符,这成为Python 3.0中的默认行为。有关更多详细信息,请参阅newline参数的文档 。注意
Python不依赖于底层操作系统的文本文件概念; 所有处理都由Python本身完成,因此与平台无关。
buffering是一个可选的整数,用于设置缓冲策略。传递0以切换缓冲关闭(仅允许在二进制模式下),1选择行缓冲(仅在文本模式下可用),并且整数> 1以指示固定大小的块缓冲区的大小(以字节为单位)。如果没有给出缓冲参数,则默认缓冲策略的工作方式如下:
二进制文件以固定大小的块缓冲; 使用启发式方法选择缓冲区的大小,尝试确定底层设备的“块大小”并重新开始
io.DEFAULT_BUFFER_SIZE
。在许多系统上,缓冲区通常为4096或8192字节长。“交互式”文本文件(
isatty()
返回的文件True
)使用行缓冲。其他文本文件使用上述策略用于二进制文件。
encoding是用于解码或编码文件的编码的名称。这应该只在文本模式下使用。默认编码取决于平台(无论
locale.getpreferredencoding()
返回),但可以使用Python支持的任何 文本编码。请参阅codecs
模块以获取支持的编码列表。errors是一个可选字符串,用于指定如何处理编码和解码错误 – 这不能在二进制模式下使用。可以使用各种标准错误处理程序(在错误处理程序下列出),但已注册的任何错误处理名称
codecs.register_error()
也是有效的。标准名称包括:'strict'
ValueError
如果存在编码错误,则引发异常。默认值None
具有相同的效果。'ignore'
ignores errors. Note that ignoring encoding errors can lead to data loss.'replace'
causes a replacement marker (such as'?'
) to be inserted where there is malformed data.'surrogateescape'
will represent any incorrect bytes as code points in the Unicode Private Use Area ranging from U+DC80 to U+DCFF. These private code points will then be turned back into the same bytes when thesurrogateescape
error handler is used when writing data. This is useful for processing files in an unknown encoding.'xmlcharrefreplace'
is only supported when writing to a file. Characters not supported by the encoding are replaced with the appropriate XML character reference&#nnn;
.'backslashreplace'
replaces malformed data by Python’s backslashed escape sequences.'namereplace'
(also only supported when writing) replaces unsupported characters with\N{...}
escape sequences.
newline controls how universal newlines mode works (it only applies to text mode). It can be
None
,''
,'\n'
,'\r'
, and'\r\n'
. It works as follows:When reading input from the stream, if newline is
None
, universal newlines mode is enabled. Lines in the input can end in'\n'
,'\r'
, or'\r\n'
, and these are translated into'\n'
before being returned to the caller. If it is''
, universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.When writing output to the stream, if newline is
None
, any'\n'
characters written are translated to the system default line separator,os.linesep
. If newline is''
or'\n'
, no translation takes place. If newline is any of the other legal values, any'\n'
characters written are translated to the given string.
If closefd is
False
and a file descriptor rather than a filename was given, the underlying file descriptor will be kept open when the file is closed. If a filename is given closefd must beTrue
(the default) otherwise an error will be raised.A custom opener can be used by passing a callable as opener. The underlying file descriptor for the file object is then obtained by calling opener with (file, flags). opener must return an open file descriptor (passing
os.open
as opener results in functionality similar to passingNone
).The newly created file is non-inheritable.
The following example uses the dir_fd parameter of the
os.open()
function to open a file relative to a given directory:>>>
>>> import os >>> dir_fd = os.open('somedir', os.O_RDONLY) >>> def opener(path, flags): ... return os.open(path, flags, dir_fd=dir_fd) ... >>> with open('spamspam.txt', 'w', opener=opener) as f: ... print('This will be written to somedir/spamspam.txt', file=f) ... >>> os.close(dir_fd) # don't leak a file descriptor
The type of file object returned by the
open()
function depends on the mode. Whenopen()
is used to open a file in a text mode ('w'
,'r'
,'wt'
,'rt'
, etc.), it returns a subclass ofio.TextIOBase
(specificallyio.TextIOWrapper
). When used to open a file in a binary mode with buffering, the returned class is a subclass ofio.BufferedIOBase
. The exact class varies: in read binary mode, it returns anio.BufferedReader
; in write binary and append binary modes, it returns anio.BufferedWriter
, and in read/write mode, it returns anio.BufferedRandom
. When buffering is disabled, the raw stream, a subclass ofio.RawIOBase
,io.FileIO
, is returned.See also the file handling modules, such as,
fileinput
,io
(whereopen()
is declared),os
,os.path
,tempfile
, andshutil
.Changed in version 3.3:
The opener parameter was added.
The
'x'
mode was added.FileExistsError
is now raised if the file opened in exclusive creation mode ('x'
) already exists.
Changed in version 3.4:
The file is now non-inheritable.
Deprecated since version 3.4, will be removed in version 4.0: The
'U'
mode.Changed in version 3.5:
If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising an
InterruptedError
exception (see PEP 475for the rationale).The
'namereplace'
error handler was added.
Changed in version 3.6:
Support added to accept objects implementing
os.PathLike
.On Windows, opening a console buffer may return a subclass of
io.RawIOBase
other thanio.FileIO
.
-
ord
(c) Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example,
ord('a')
returns the integer97
andord('€')
(Euro sign) returns8364
. This is the inverse ofchr()
.
-
pow
(x, y[, z]) Return x to the power y; if z is present, return x to the power y, modulo z (computed more efficiently than
pow(x,y) % z
). The two-argument formpow(x, y)
is equivalent to using the power operator:x**y
.The arguments must have numeric types. With mixed operand types, the coercion rules for binary arithmetic operators apply. For
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
returns100
, but10**-2
returns0.01
. If the second argument is negative, the third argument must be omitted. If z is present, x and y must be of integer types, and y must be non-negative.
-
print
(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False) Print objects to the text stream file, separated by sep and followed by end. sep, end, file and flush, if present, must be given as keyword arguments.
All non-keyword arguments are converted to strings like
str()
does and written to the stream, separated by sepand followed by end. Both sep and end must be strings; they can also beNone
, which means to use the default values. If no objects are given,print()
will just write end.The file argument must be an object with a
write(string)
method; if it is not present orNone
,sys.stdout
will be used. Since printed arguments are converted to text strings,print()
cannot be used with binary mode file objects. For these, usefile.write(...)
instead.Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.
Changed in version 3.3: Added the flush keyword argument.
- class
property
(fget=None, fset=None, fdel=None, doc=None) Return a property attribute.
fget is a function for getting an attribute value. fset is a function for setting an attribute value. fdel is a function for deleting an attribute value. And doc creates a docstring for the attribute.
A typical use is to define a managed attribute
x
:class C: 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.")
If c is an instance of C,
c.x
will invoke the getter,c.x = value
will invoke the setter anddel c.x
the deleter.If given, doc will be the docstring of the property attribute. Otherwise, the property will copy fget’s docstring (if it exists). This makes it possible to create read-only properties easily using
property()
as a decorator:class Parrot: def __init__(self): self._voltage = 100000 @property def voltage(self): """Get the current voltage.""" return self._voltage
The
@property
decorator turns thevoltage()
method into a “getter” for a read-only attribute with the same name, and it sets the docstring for voltage to “Get the current voltage.”A property object has
getter
,setter
, anddeleter
methods usable as decorators that create a copy of the property with the corresponding accessor function set to the decorated function. This is best explained with an example:class C: 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
This code is exactly equivalent to the first example. Be sure to give the additional functions the same name as the original property (
x
in this case.)The returned property object also has the attributes
fget
,fset
, andfdel
corresponding to the constructor arguments.Changed in version 3.5: The docstrings of property objects are now writeable.
-
range
(stop) -
range
(start, stop[, step]) Rather than being a function,
range
is actually an immutable sequence type, as documented in Ranges and Sequence Types — list, tuple, range.
-
repr
(object) Return a string containing a printable representation of an 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()
, 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__()
method.
-
reversed
(seq) Return a reverse iterator. seq must be an object which has a
__reversed__()
method or supports the sequence protocol (the__len__()
method and the__getitem__()
method with integer arguments starting at0
).
-
round
(number[, ndigits]) Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is
None
, it returns the nearest integer to its input.For the built-in types supporting
round()
, values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, bothround(0.5)
andround(-0.5)
are0
, andround(1.5)
is2
). Any integer value is valid for ndigits (positive, zero, or negative). The return value is an integer if ndigits is omitted orNone
. Otherwise the return value has the same type as number.For a general Python object
number
,round
delegates tonumber.__round__
.Note
The behavior of
round()
for floats can be surprising: for example,round(2.675, 2)
gives2.67
instead of the expected2.68
. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.
- class
set
([iterable]) Return a new
set
object, optionally with elements taken from iterable.set
is a built-in class. Seeset
and Set Types — set, frozenset for documentation about this class.For other containers see the built-in
frozenset
,list
,tuple
, anddict
classes, as well as thecollections
module.
-
setattr
(object, name, value) This is the counterpart of
getattr()
. The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example,setattr(x, 'foobar', 123)
is equivalent tox.foobar = 123
.
- class
slice
(stop) - class
slice
(start, stop[, step]) Return a slice object representing the set of indices specified by
range(start, stop, step)
. The start and steparguments default toNone
. Slice objects have read-only data attributesstart
,stop
andstep
which merely return the argument values (or their default). They have no other explicit functionality; however they are used by Numerical Python and other third party extensions. Slice objects are also generated when extended indexing syntax is used. For example:a[start:stop:step]
ora[start:stop, i]
. Seeitertools.islice()
for an alternate version that returns an iterator.
-
sorted
(iterable, *, key=None, reverse=False) Return a new sorted list from the items in iterable.
Has two optional arguments which must be specified as keyword arguments.
key specifies a function of one argument that is used to extract a comparison key from each element in iterable(for example,
key=str.lower
). The default value isNone
(compare the elements directly).reverse is a boolean value. If set to
True
, then the list elements are sorted as if each comparison were reversed.Use
functools.cmp_to_key()
to convert an old-style cmp function to a key function.The built-in
sorted()
function is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).For sorting examples and a brief sorting tutorial, see Sorting HOW TO.
-
@
staticmethod
Transform a method into a static method.
A static method does not receive an implicit first argument. To declare a static method, use this idiom:
class C: @staticmethod def f(arg1, arg2, ...): ...
The
@staticmethod
form is a function decorator – see Function definitions for details.A static method can be called either on the class (such as
C.f()
) or on an instance (such asC().f()
).Static methods in Python are similar to those found in Java or C++. Also see
classmethod()
for a variant that is useful for creating alternate class constructors.Like all decorators, it is also possible to call
staticmethod
as a regular function and do something with its result. This is needed in some cases where you need a reference to a function from a class body and you want to avoid the automatic transformation to instance method. For these cases, use this idiom:class C: builtin_open = staticmethod(open)
For more information on static methods, see The standard type hierarchy.
- class
str
(object=”) - class
str
(object=b”, encoding=’utf-8′, errors=’strict’) Return a
str
version of object. Seestr()
for details.str
is the built-in string class. For general information about strings, see Text Sequence Type — str.
-
sum
(iterable[, start]) Sums start and the items of an iterable from left to right and returns the total. start defaults to
0
. The iterable’s items are normally numbers, and the start value is not allowed to be a string.For some use cases, there are good alternatives to
sum()
. The preferred, fast way to concatenate a sequence of strings is by calling''.join(sequence)
. To add floating point values with extended precision, seemath.fsum()
. To concatenate a series of iterables, consider usingitertools.chain()
.
-
super
([type[, object-or-type]]) Return a proxy object that delegates method calls to a parent or sibling class of 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__
attribute of the type lists the method resolution search order used by bothgetattr()
andsuper()
. 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).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().method(arg) # This does the same thing as: # super(C, self).method(arg)
Note that
super()
is implemented as part of the binding process for explicit dotted attribute lookups such assuper().__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 assuper()[name]
.Also note that, aside from the zero argument form,
super()
is not limited to use inside methods. The two argument form specifies the arguments exactly and makes the appropriate references. The zero argument form only works inside a class definition, as the compiler fills in the necessary details to correctly retrieve the class being defined, as well as accessing the current instance for ordinary methods.For practical suggestions on how to design cooperative classes using
super()
, see guide to using super().
-
tuple
([iterable]) Rather than being a function,
tuple
is actually an immutable sequence type, as documented in Tuples and Sequence Types — list, tuple, range.
- class
type
(object) - class
type
(name, bases, dict) With one argument, return the type of an object. The return value is a type object and generally the same object as returned by
object.__class__
.The
isinstance()
built-in function is recommended for testing the type of an object, because it takes subclasses into account.With three arguments, return a new type object. This is essentially a dynamic form of the
class
statement. The name string is the class name and becomes the__name__
attribute; the bases tuple itemizes the base classes and becomes the__bases__
attribute; and the dict dictionary is the namespace containing definitions for class body and is copied to a standard dictionary to become the__dict__
attribute. For example, the following two statements create identicaltype
objects:>>> class X: ... a = 1 ... >>> X = type('X', (object,), dict(a=1))
See also Type Objects.
Changed in version 3.6: Subclasses of
type
which don’t overridetype.__new__
may no longer use the one-argument form to get the type of an object.
-
vars
([object]) Return the
__dict__
attribute for a module, class, instance, or any other object with a__dict__
attribute.Objects such as modules and instances have an updateable
__dict__
attribute; however, other objects may have write restrictions on their__dict__
attributes (for example, classes use atypes.MappingProxyType
to prevent direct dictionary updates).Without an argument,
vars()
acts likelocals()
. Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.
-
zip
(*iterables) Make an iterator that aggregates elements from each of the iterables.
Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator. Equivalent to:
def zip(*iterables): # zip('ABCD', 'xy') --> Ax By sentinel = object() iterators = [iter(it) for it in iterables] while iterators: result = [] for it in iterators: elem = next(it, sentinel) if elem is sentinel: return result.append(elem) yield tuple(result)
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)
. This repeats the same iteratorn
times so that each output tuple has the result ofn
calls to the iterator. This has the effect of dividing the input into n-length chunks.zip()
should only be used with unequal length inputs when you don’t care about trailing, unmatched values from the longer iterables. If those values are important, useitertools.zip_longest()
instead.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) >>> list(zipped) [(1, 4), (2, 5), (3, 6)] >>> x2, y2 = zip(*zip(x, y)) >>> x == list(x2) and y == list(y2) True
-
__import__
(name, globals=None, locals=None, fromlist=(), level=0) Note
This is an advanced function that is not needed in everyday Python programming, unlike
importlib.import_module()
.This function is invoked by the
import
statement. It can be replaced (by importing thebuiltins
module and assigning tobuiltins.__import__
) in order to change semantics of theimport
statement, but doing so is strongly discouraged as it is usually simpler to use import hooks (see PEP 302) to attain the same goals and does not cause issues with code which assumes the default import implementation is in use. Direct use of__import__()
is also discouraged in favor ofimportlib.import_module()
.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.
0
(the default) 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__()
(see PEP 328 for the details).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
import spam
results in bytecode resembling the following code:spam = __import__('spam', globals(), locals(), [], 0)
The statement
import spam.ham
results in this call:spam = __import__('spam.ham', globals(), locals(), [], 0)
Note how
__import__()
returns the toplevel module here because this is the object that is bound to a name by theimport
statement.On the other hand, the statement
from spam.ham import eggs, sausage as saus
results in_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0) eggs = _temp.eggs saus = _temp.sausage
Here, the
spam.ham
module is returned from__import__()
. From this object, the names to import are retrieved and assigned to their respective names.If you simply want to import a module (potentially within a package) by name, use
importlib.import_module()
.Changed in version 3.3: Negative values for level are no longer supported (which also changes the default value to 0).
Footnotes
- 1
请注意,解析器只接受Unix风格的行尾约定。如果您正在从文件中读取代码,请确保使用换行转换模式来转换Windows或Mac样式的换行符。