python__007内置函数
本文摘自: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
(对象) -
如,由返回的字符串中返回一个包含对象的可打印表示一个字符串,但逃避非ascii字符 使用
\x
,\u
或\u
逃逸。这会生成一个类似于python 2 中返回的字符串。
-
bin
(x ) -
将整数转换为前缀为“0b”的二进制字符串。结果是一个有效的python表达式。如果x不是python 对象,则必须定义一个返回整数的方法。一些例子:
>>> bin(3) '0b11' >>> bin(-10) '-0b1010'
如果需要前缀“0b”,您可以使用以下任一方法。
>>> format(14, '#b'), format(14, 'b') ('0b1110', '1110') >>> f'{14:#b}', f'{14:b}' ('0b1110', '1110')
另请参阅以获取更多信息。
-
class
bool
([ x ] ) -
返回一个布尔值,即
true
或者之一false
。 使用标准转换x。如果x为false或省略,则返回; 否则它会返回。的 类是的子类(参见)。它不能进一步细分。它的唯一实例是和 (参见)。false
true
false
true
在版本3.7中更改:x现在是仅位置参数。
-
breakpoint
(* args,** kws ) -
此函数会将您置于调用站点的调试器中。具体来说,它呼叫,传递
args
和kws
直接通过。默认情况下,sys.breakpointhook()
调用 不需要参数。在这种情况下,它纯粹是一个便利功能,因此您不必显式导入pdb
或输入尽可能多的代码来进入调试器。但是, 可以设置为其他一些功能并 自动调用它,允许您进入选择的调试器。版本3.7中的新功能。
-
class
bytearray
([ source [,encoding [,errors ] ] ] ) -
返回一个新的字节数组。的类是整数的范围为0 <= x一个可变的序列<256它具有最的可变序列,在所描述的常规方法,以及大多数方法,该类型已见字节和bytearray操作。
可选的source参数可用于以几种不同的方式初始化数组:
-
如果它是一个字符串,您还必须提供编码(和可选的, 错误)参数; 然后使用将字符串转换为字节。
-
如果它是一个整数,则该数组将具有该大小,并将使用空字节进行初始化。
-
如果它是符合缓冲区接口的对象,则将使用该对象的只读缓冲区来初始化bytes数组。
-
如果它是可迭代的,则它必须是范围内的可迭代整数 ,它们用作数组的初始内容。
0 <= x < 256
如果没有参数,则会创建一个大小为0的数组。
另请参见和bytearray对象。
-
-
class
bytes
([ source [,encoding [,errors ] ] ] ) -
返回一个新的“bytes”对象,该对象是该范围内不可变的整数序列。 是一个不可变的版本 - 它具有相同的非变异方法和相同的索引和切片行为。
0 <= x < 256
因此,构造函数参数被解释为。
也可以使用文字创建字节对象,请参阅。
另请参见,,以及。
-
callable
(对象) -
true
如果object参数显示为可调用false
则返回,否则返回。如果返回true,则调用仍然可能失败,但如果调用失败,则调用对象将永远不会成功。请注意,类是可调用的(调用类会返回一个新实例); 如果实例的类具有方法,则它们是可调用的。版本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静态方法不同。如果你想要那些,请参阅。
有关类方法的更多信息,请参阅。
-
compile
(source,filename,mode,flags = 0,dont_inherit = false,optimize = -1 ) -
将源代码编译为代码或ast对象。代码对象可以由
exec()
或执行。 source可以是普通字符串,字节字符串或ast对象。有关如何使用ast对象的信息,请参阅模块文档。该文件名参数应该给从代码读取的文件; 如果没有从文件中读取(
'<string>'
通常使用),则传递一些可识别的值。该模式参数指定什么样的代码必须进行编译; 它可以是
'exec'
,如果源包含的语句序列的,'eval'
如果它由一个单一的表达的,或者'single'
如果它由单个交互式声明的(在后一种情况下,计算结果为比其他东西表达式语句none
将被打印)。可选参数flags和dont_inherit控制影响源的编译。如果两者都不存在(或两者都为零),则使用在调用的代码中生效的未来语句编译代码。如果 给出flags参数且dont_inherit不是(或为零),那么除了将要使用的那些之外,还使用flags参数指定的future语句。如果dont_inherit是一个非零整数,那么flags参数就是它 - 忽略了对编译调用有效的未来语句。
将来的语句由位指定,这些位可以按位or运算以指定多个语句。指定给定特征所需的位域可以作为模块中实例的
compiler_flag
属性找到。_feature
参数optimize指定编译器的优化级别; 默认值
-1
选择由-o
选项给出的解释器的优化级别。显式级别是0
(没有优化;__debug__
是真的),1
(断言被删除,__debug__
是假的)或2
(文档字符串也被删除)。syntaxerror
如果编译的源无效,并且valueerror
源包含空字节,则此函数引发。如果要将python代码解析为其ast表示,请参阅 。
注意
在
'single'
或'eval'
模式下使用多行代码编译字符串时,输入必须至少由一个换行符终止。这有助于检测模块中不完整和完整的语句。警告
由于python ast编译器中的堆栈深度限制,在编译为ast对象时,可能会使python解释器崩溃并使用足够大/复杂的字符串。
版本3.2中已更改:允许使用windows和mac换行符。在
'exec'
模式下输入也不必再以换行符结束。添加了optimize参数。在版本3.5中更改:以前
typeerror
在源中遇到空字节时引发。
-
class
complex
([ real [,imag ] ] ) -
返回值为real + imag * 1j的复数或将字符串或数字转换为复数。如果第一个参数是一个字符串,它将被解释为一个复数,并且必须在没有第二个参数的情况下调用该函数。第二个参数永远不能是字符串。每个参数可以是任何数字类型(包括复数)。如果imag被省略,默认为零,并且构造用作数字转换等 和。如果省略两个参数,则返回
0j
。注意
从字符串转换时,字符串不得包含中心
+
或-
运算符周围的空格。例如,complex('1+2j')
很好,但提高 。complex('1 + 2j')
valueerror
复杂类型在numeric types中描述。
在版本3.6中更改:允许使用下划线对数字进行分组,如代码文字中所示。
-
delattr
(对象,名称) -
这是一个亲戚
setattr()
。参数是一个对象和一个字符串。该字符串必须是对象属性之一的名称。如果对象允许,该函数将删除命名属性。例如,相当于。delattr(x, 'foobar')
del x.foobar
-
上课
dict
(** kwarg ) -
class
dict
(mapping,** kwarg ) -
class
dict
(iterable,** kwarg ) -
创建一个新的字典。该对象是字典类。有关此类的文档,请参阅和。
对于其他容器,请参阅内置的 in ,和 类以及模块。
-
dir
([ 对象] ) -
如果没有参数,则返回当前本地范围中的名称列表。使用参数,尝试返回该对象的有效属性列表。
如果对象具有名为的方法,则将调用此方法,并且必须返回属性列表。这允许实现自定义或函数的对象自 定义
dir()
报告其属性的方式 。如果对象未提供,则该函数会尽力从对象的属性(如果已定义)和其类型对象中收集信息。结果列表不一定完整,并且在对象具有自定义时可能不准确。
默认
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必须是一个序列,一个 或一些支持迭代的对象。返回的迭代器的方法 返回一个包含计数的元组(从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__
字典。如果省略两个字典,则表达式在调用的环境中执行。返回值是计算表达式的结果。语法错误报告为异常。例:>>> x = 1 >>> eval('x+1') 2
此函数还可用于执行任意代码对象(例如由其创建的代码对象)。在这种情况下,传递代码对象而不是字符串。如果代码对象已经被编译
'exec'
为 模式的说法,“返回值会none
。提示:
exec()
函数支持动态执行语句。的和功能返回当前全球和本地词典,分别,其可以是通过以绕过使用有用或exec()
。请参阅可以安全地使用仅包含文字的表达式来评估字符串的函数。
-
exec
(object [,globals [,locals ] ] ) -
此函数支持python代码的动态执行。object必须是字符串或代码对象。如果它是一个字符串,则将该字符串解析为一组python语句,然后执行该语句(除非发生语法错误)。如果它是代码对象,则只执行它。在所有情况下,执行的代码应该作为文件输入有效(请参见“参考手册”中的“文件输入”部分)。请注意, 即使在传递给函数的代码的上下文中,也不能在函数定义之外使用和语句
exec()
。返回值是none
。在所有情况下,如果省略可选部分,则代码在当前范围内执行。如果只提供全局变量,则它必须是字典,它将用于全局变量和局部变量。如果全局和 当地人给出,它们分别用于全局和局部变量。如果提供,则locals可以是任何映射对象。请记住,在模块级别,全局变量和本地变量是相同的字典。如果exec获得两个单独的对象作为全局变量和局部变量,则代码将被执行,就像它嵌入在类定义中一样。
如果全局字典不包含键的值, 则在该键下插入对内置模块 的字典的引用。这样,您可以通过在传递给自己的字典之前将自己的字典插入到全局变量中来控制已执行代码可用的 内置函数 。
__builtins__
__builtins__
exec()
注意
在建 -in功能和返回当前的全局和局部字典,分别,这可能是传递用作第二个和第三个参数有用
exec()
。注意
默认的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
请参阅补充函数,该函数返回iterable的元素,该函数返回false。
-
class
float
([ x ] ) -
返回由数字或字符串x构造的浮点数。
如果参数是一个字符串,它应该包含一个十进制数字,可选地以符号开头,并且可选地嵌入在空格中。可选标志可以是
'+'
或'-'
; 一个'+'
符号具有上产生的值没有影响。参数也可以是表示nan(非数字)或正或负无穷大的字符串。更确切地说,在删除前导和尾随空格字符后,输入必须符合以下语法:sign :: =“+”| “ - ” infinity :: =“infinity”| “inf” nan :: =“nan” numeric_value :: = floatnumber| infinity| numeric_string :: = [ ]nan signnumeric_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中描述。
在版本3.6中更改:允许使用下划线对数字进行分组,如代码文字中所示。
在版本3.7中更改:x现在是仅位置参数。
-
format
(value [,format_spec ] ) -
将值转换为“格式化”表示,由format_spec控制 。format_spec的解释将取决于value参数的类型,但是大多数内置类型都使用标准格式化语法:format specification mini-language。
默认的format_spec是一个空字符串,通常与调用具有相同的效果。
转换为 在搜索值的方法时绕过实例字典的调用。一 ,如果该方法搜索到达引发异常 和format_spec非空,或者这两个 format_spec或返回值是不是字符串。
format(value,format_spec)
type(value).__format__(value, format_spec)
typeerror
在版本3.4中更改: 如果format_spec不是空字符串,则
object().__format__(format_spec)
引发。typeerror
-
class
frozenset
([ iterable ] ) -
返回一个新对象,可选地包含从iterable中获取的元素 。
frozenset
是一个内置的类。有关的文档请参阅和 。对于其他容器看到内置 -in ,, ,和类,还有 模块。
-
getattr
(对象,名称[,默认] ) -
返回object的named属性的值。 name必须是一个字符串。如果字符串是对象属性之一的名称,则结果是该属性的值。例如,相当于 。如果named属性不存在,则返回default(如果提供),否则引发。
getattr(x,'foobar')
x.foobar
attributeerror
-
globals
() -
返回表示当前全局符号表的字典。这始终是当前模块的字典(在函数或方法内部,这是定义它的模块,而不是调用它的模块)。
-
hasattr
(对象,名称) -
参数是一个对象和一个字符串。结果是,
true
如果字符串是对象属性之一的名称,false
如果不是。(这是通过调用并查看它是否会引发来实现的。)getattr(object, name)
attributeerror
-
hash
(对象) -
返回对象的哈希值(如果有的话)。哈希值是整数。它们用于在字典查找期间快速比较字典键。比较相等的数字值具有相同的哈希值(即使它们具有不同的类型,如1和1.0的情况)。
注意
对于具有自定义方法的对象,请注意 根据主机的位宽截断返回值。详情请见。
-
help
([ 对象] ) -
调用内置的帮助系统。(此函数用于交互式使用。)如果未给出参数,则交互式帮助系统将在解释器控制台上启动。如果参数是字符串,则查找字符串作为模块,函数,类,方法,关键字或文档主题的名称,并在控制台上打印帮助页面。如果参数是任何其他类型的对象,则会生成对象的帮助页面。
请注意,如果函数的参数列表中出现斜杠(/),则在调用时,意味着斜杠之前的参数仅为位置参数。有关详细信息,请参阅 有关仅位置参数的faq条目。
此函数由模块添加到内置命名空间。
版本3.4中的更改:更改为并且表示报告的可调用签名现在更全面和一致。
-
hex
(x ) -
将整数转换为带有前缀“0x”的小写十六进制字符串。如果x不是python 对象,则必须定义一个返回整数的 方法。一些例子:
>>> 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')
另请参阅以获取更多信息。
另请参阅
int()
使用16的基数将十六进制字符串转换为整数。注意
要获取float的十六进制字符串表示形式,请使用该 方法。
-
id
(对象) -
返回对象的“标识”。这是一个整数,在该生命周期内保证该对象是唯一且恒定的。具有非重叠寿命的两个对象可以具有相同的
id()
值。cpython实现细节:这是内存中对象的地址。
-
input
([ 提示] ) -
如果存在prompt参数,则将其写入标准输出而不带尾随换行符。然后,该函数从输入中读取一行,将其转换为字符串(剥离尾部换行符),然后返回该行。读取eof时,
eoferror
会引发。例:>>> s = input('--> ') --> monty python's flying circus >>> s "monty python's flying circus"
如果
readline
模块已加载,则将使用它来提供精细的行编辑和历史记录功能。
-
class
int
([ x ] ) -
class
int
(x,base = 10 ) -
返回由数字或字符串x构造的整数对象,
0
如果没有给出参数,则返回 。如果x定义,则int(x)
返回x.__int__()
。如果x定义,则返回x.__trunc__()
。对于浮点数,这会截断为零。如果x不是数字或如果基给出,则x必须是一个字符串, 或代表一个实例在基数基。可选地,文字可以在
+
或之前-
(之间没有空格)并且由空格包围。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)
整数类型在描述。
在版本3.4中更改:如果base不是实例,并且基础对象具有 方法,则调用该方法以获取基础的整数。以前的版本使用 而不是。
在版本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 ] ) -
返回一个对象。根据第二个参数的存在,第一个参数的解释非常不同。如果没有第二个参数,对象必须是支持迭代协议(方法)的集合对象,或者它必须支持序列协议(从整数参数开始的方法
0
)。如果它不支持这些协议中的任何一个,typeerror
则引发。如果给出第二个参数sentinel,则object必须是可调用对象。在这种情况下创建的迭代器将为每个对其方法的调用调用没有参数的 对象 ; 如果返回的值等于 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 ] ) -
实际上,它不是一个函数,而是一个可变序列类型,如和。
-
locals
() -
更新并返回表示当前本地符号表的字典。*变量在函数块中调用时返回,但不在类块中调用。请注意,在模块级别, 并且是相同的字典。
注意
不应修改此词典的内容; 更改可能不会影响解释器使用的本地和*变量的值。
-
map
(功能,可迭代,...... ) -
返回一个迭代器,它将函数应用于每个iterable项,从而产生结果。如果传递了其他可迭代参数,则 函数必须采用那么多参数,并且并行地应用于所有迭代的项。对于多个迭代,迭代器在最短的iterable耗尽时停止。对于函数输入已经安排到参数元组的情况,请参阅。
-
max
(iterable,* [,key,default ] ) -
max
(arg1,arg2,* args [,key ] ) -
返回可迭代中的最大项或两个或多个参数中的最大项。
如果提供了一个位置参数,则它应该是。返回iterable中的最大项。如果提供了两个或多个位置参数,则返回最大的位置参数。
有两个可选的仅关键字参数。该关键参数指定一个参数的排序功能,类似于用于。该 默认参数指定的对象返回如果提供的迭代是空的。如果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中的最小项。如果提供了两个或多个位置参数,则返回最小的位置参数。
有两个可选的仅关键字参数。该关键参数指定一个参数的排序功能,类似于用于。该 默认参数指定的对象返回如果提供的迭代是空的。如果iterable为空并且未提供default,
valueerror
则引发a。如果多个项目是最小的,则该函数返回遇到的第一个项目。这与其他排序稳定性保留工具(例如和)一致。
sorted(iterable, key=keyfunc)[0]
heapq.nsmallest(1, iterable, key=keyfunc)
在新版本3.4:在默认情况下只有关键字的说法。
-
next
(迭代器[,默认] ) -
通过调用其 方法从迭代器中检索下一个项目。如果给定default,则在迭代器耗尽时返回,否则
stopiteration
引发。
-
类
object
-
返回一个新的无特征对象。 是所有课程的基础。它具有所有python类实例共有的方法。此函数不接受任何参数。
注意
没有不有,所以你不能指定任意属性的实例类。
-
oct
(x ) -
将整数转换为前缀为“0o”的八进制字符串。结果是一个有效的python表达式。如果x不是python 对象,则必须定义一个返回整数的方法。例如:
>>> 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')
另请参阅以获取更多信息。
-
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 参数中)将内容作为对象返回,而不进行任何解码。在文本模式(默认情况下,或者't'
包含在mode参数中)时,文件的内容将返回为,首先使用平台相关编码或使用指定的编码(如果给定)对字节进行解码 。允许使用其他模式字符
'u'
,该字符不再具有任何效果,并且被视为已弃用。它以前在文本模式下启用了 ,这成为python 3.0中的默认行为。有关更多详细信息,请参阅参数的文档 。注意
python不依赖于底层操作系统的文本文件概念; 所有处理都由python本身完成,因此与平台无关。
buffering是一个可选的整数,用于设置缓冲策略。传递0以切换缓冲关闭(仅允许在二进制模式下),1选择行缓冲(仅在文本模式下可用),并且整数> 1以指示固定大小的块缓冲区的大小(以字节为单位)。如果没有给出缓冲参数,则默认缓冲策略的工作方式如下:
-
二进制文件以固定大小的块缓冲; 使用启发式方法选择缓冲区的大小,尝试确定底层设备的“块大小”并重新开始
io.default_buffer_size
。在许多系统上,缓冲区通常为4096或8192字节长。 -
“交互式”文本文件(
isatty()
返回的文件true
)使用行缓冲。其他文本文件使用上述策略用于二进制文件。
encoding是用于解码或编码文件的编码的名称。这应该只在文本模式下使用。默认编码取决于平台(无论返回),但可以使用python支持的任何 。请参阅模块以获取支持的编码列表。
errors是一个可选字符串,用于指定如何处理编码和解码错误 - 这不能在二进制模式下使用。可以使用各种标准错误处理程序(在),但已注册的任何错误处理名称 也是有效的。标准名称包括:
-
'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 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, . 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 as opener results in functionality similar to passing
none
).the newly created file is .
the following example uses the parameter of the 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 returned by the function depends on the mode. when 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
(where 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 of .
-
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 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 does and written to the stream, separated by sepand followed by end. both sep and end must be strings; they can also be
none
, which means to use the default values. if no objects are given, will just write end.the file argument must be an object with a
write(string)
method; if it is not present ornone
, will be used. since printed arguments are converted to text strings, 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 as a :
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, 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 , 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 method.
-
reversed
(seq) -
return a reverse . seq must be an object which has a method or supports the sequence protocol (the method and the method with integer arguments starting at
0
).
-
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 , 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, both
round(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 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 object, optionally with elements taken from iterable.
set
is a built-in class. see and set types — set, frozenset for documentation about this class.for other containers see the built-in , , , and classes, as well as the
collections
module.
-
setattr
(object, name, value) -
this is the counterpart of . 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 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]
. see 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 to convert an old-style cmp function to a key function.
the built-in 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 – 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 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 version of object. see for details.
str
is the built-in string . 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 . the preferred, fast way to concatenate a sequence of strings is by calling
''.join(sequence)
. to add floating point values with extended precision, see . to concatenate a series of iterables, consider using .
-
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 except that the type itself is skipped.
the attribute of the type lists the method resolution search order used by both and . 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 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 method for searching classes in a predictable order that supports cooperative multiple inheritance. accordingly, is undefined for implicit lookups using statements or operators such assuper()[name]
.also note that, aside from the zero argument form, 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 , see .
-
tuple
([iterable]) -
rather than being a function, 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 .
the 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 statement. the name string is the class name and becomes the attribute; the bases tuple itemizes the base classes and becomes the attribute; and the dict dictionary is the namespace containing definitions for class body and is copied to a standard dictionary to become the attribute. for example, the following two statements create identical objects:
>>> class x: ... a = 1 ... >>> x = type('x', (object,), dict(a=1))
see also type objects.
changed in version 3.6: subclasses of which don’t override
type.__new__
may no longer use the one-argument form to get the type of an object.
-
vars
([object]) -
return the attribute for a module, class, instance, or any other object with a attribute.
objects such as modules and instances have an updateable attribute; however, other objects may have write restrictions on their attributes (for example, classes use a
types.mappingproxytype
to prevent direct dictionary updates).without an argument, acts like . 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.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, use instead.
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.
this function is invoked by the statement. it can be replaced (by importing the module and assigning to
builtins.__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 is also discouraged in favor of .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 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 (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 returns the toplevel module here because this is the object that is bound to a name by the 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 . 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 .
changed in version 3.3: negative values for level are no longer supported (which also changes the default value to 0).
footnotes
-
请注意,解析器只接受unix风格的行尾约定。如果您正在从文件中读取代码,请确保使用换行转换模式来转换windows或mac样式的换行符。
上一篇: Kafka监控工具汇总
下一篇: React入门-JSX和虚拟dom