Python3内建函数学习笔记

查看Python3当前有哪些内建函数的最好方式就是去看官方文档:

https://docs.python.org/3/library/functions.html

学习笔记也是跟着官方文档的排序,一个个看下来。纯属个人的学习笔记和个人理解,错误之处恳请大佬们不吝指正!

 

abs(x)

(一).官方文档原文

Return the absolute value of a number. The argument may be an integer or a floating point number. If the argument is a complex number, its magnitude is returned.

(二).大意

返回一个数字的绝对值。参数可以是整形或者浮点型。如果参数是一个复数,则返回其大小。

(三).演示

 

all(iterable)

(一).官方文档原文

Return True if all elements of the iterable are true (or if the iterable is empty).

(二).大意

当一个可迭代对象中所有元素都为真的时候,返回True。如果这个可迭代为空,同样也返回Ture

(三).实现原理

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True
View Code

遍历整个可迭代对象,当遇到某个元素为False的时候,not对它进行取反了,条件为真就会进入if语句中,直接结束整个函数,并返回False

当可迭代对象为空的时候,for循环它遍历不到任何的东西,就会跳过整个for循环语句块,执行了最后的一条语句,返回了True

(四).演示

参数必须是一个可迭代的对象!

 

any(iterable)

(一).官方文档原文

Return True if any element of the iterable is true. If the iterable is empty, return False.

(二).大意

只要可迭代对象中有任意一个元素为真,那么就返回True。如果这个可迭代对象为空,则返回False

(三).实现原理

对比上面的all()来看,其实就是判断语句中少了not这个取反。all()必须全部为真才是True,any()只要有一个为真那就是True。

区别在于:当可迭代对象为空的时候,all()返回True,而any()返回False

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
View Code

(四).演示

 

ascii(object)

(一).官方文档原文

As repr(), return a string containing a printable representation of an object, but escape the non-ASCII characters in the string returned by repr() using \x, \u or \U escapes.

(二).大意

使用repr()来打印,返回这个对象的ASCII码字符串,如果对象不是ASCII字符,则使用\x, \u, \U来转义。

(三).演示

 

bin(x)

(一).官方文档原文

Convert an integer number to a binary string prefixed with "0b". The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.

(二).大意

将一个整形数字转换成以"0b"开头的二进制字符串,结果是一个有效的Python表达式。如果x不是Python的int对象,则必须定义一个返回整数的__index__()方法。

(三).演示

 

 

class bool([x])

(一).官方文档原文

Return a Boolean value, i.e. one of True or False. x is converted using the standard truth testing procedure.

If x is false or omitted, this returns False; otherwise it returns True.

The bool class is a subclass of int (see Numeric Types — int, float, complex).

It cannot be subclassed further. Its only instances are False and True (see Boolean Values).

Changed in version 3.7: x is now a positional-only parameter.

(二).大意

返回一个布尔值:True/False,使用标准真值测试程序来判定参数x是否为真。

如果参数为假或缺省,将会返回False,除此之外都会返回True

bool类是int的子类,它不能再被继承,它的唯一实例是False和True。

从Python3.7开始,x现在是仅位置参数。

(三).演示

 

 

breakpoint(*args, **kws)

(一).官方文档原文

This function drops you into the debugger at the call site. Specifically, it calls sys.breakpointhook(), passing args and kws straight through.

By default, sys.breakpointhook() calls pdb.set_trace() expecting no arguments. In this case, it is purely a convenience function so you don’t have to explicitly import pdb or type as much code to enter the debugger.

However, sys.breakpointhook() can be set to some other function and breakpoint() will automatically call that, allowing you to drop into the debugger of choice.

New in version 3.7.

(二).大意

这个函数会使你进入调试模式。具体来说,它调用sys.breakpointhook(),直接传递args和kws。

默认情况下,sys.breakpointhook()会调用pdb.set_trace(),且不期望有参数传递。在这种情况下,它纯粹是一个便利功能,因此不必显式地导入pdb或输入尽可能多的代码来进入调试器。

然后,sys.breakpointhook()可以设置为一些其他函数,breakpoint()会自动调用它,允许你进入选择的调试器。

Python3.7.0开始才有的新功能。

(三).演示

breakpoint()其实就是一个内置的简易调试器,这行代码相当于一个断点,遇到这行代码,就进入了python内建的简易调试器模式

 

 

class bytearray([source[, encoding[, errors]]])

(一).官方文档原文

Return a new array of bytes. The bytearray class is a mutable sequence of integers in the range 0 <= x < 256.

It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Bytearray Operations.

The optional source parameter can be used to initialize the array in a few different ways:

If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().

If it is an integer, the array will have that size and will be initialized with null bytes.

If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.

If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.

Without an argument, an array of size 0 is created.

See also Binary Sequence Types — bytes, bytearray, memoryview and Bytearray Objects.

(二).大意

返回一个新的字节数组。bytearray类是 0 <= x < 256 范围内的可变整数序列。它具有可变序列的大多数常用方法,在可变序列类型中有所描述,以及字节类型具有的大多数方法,参见Bytes和Bytearray Operations。

可选参数source,可用于初始化数组,有以下几种不同的方式:

如果是一个字符串,必须提供编码格式(errors参数可选)参数。然后,bytearray()使用str.encode()将字符串转换为字节。

如果它是一个整数,则该数组将具有该大小,并将使用空字节进行初始化。

如果它是符合缓冲区接口的对象,则将使用该对象的只读缓冲区来初始化bytes数组。

如果它是可迭代对象,它必须是个在 0 <= x < 256 范围内可迭代对象,它们用作数组的初始内容。

如果没有参数,则会创建一个大小为0的数组。

(三).演示

 

class bytes([source[, encoding[, errors]]])

(一).官方文档原文

Return a new “bytes” object, which is an immutable sequence of integers in the range 0 <= x < 256. bytes is an immutable version of bytearray – it has the same non-mutating methods and the same indexing and slicing behavior.

Accordingly, constructor arguments are interpreted as for bytearray().

Bytes objects can also be created with literals, see String and Bytes literals.

See also Binary Sequence Types — bytes, bytearray, memoryview, Bytes Objects, and Bytes and Bytearray Operations.

(二).大意

返回一个新的"bytes"对象,它是 0 <= x < 256 范围内的不可变整数序列。字节是bytearray的不可变版本 - 它具有相同的非变异方法和相同的索引和切片行为。

因此,构造函数参数被解释为bytearray()。也可以使用文字创建字节对象。

(三).演示

 

callable(object)

(一).官方文档原文

Return True if the object argument appears callable, 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); instances are callable if their class has a __call__() method.

New in version 3.2: This function was first removed in Python 3.0 and then brought back in Python 3.2.

(二).大意

如果对象参数显示为可调用,则返回True,否则返回False。如果返回true,则调用仍然可能失败,但如果调用失败,则调用对象将永远不会成功。

注意,类是可调用的(调用类会返回一个新实例);实例的类具有__call __()方法,则它们是可调用的。

(三).演示

 

chr(i)

(一).官方文档原文

Return the string representing a character whose Unicode code point is the integer i.

For example, chr(97) returns the string 'a', while chr(8364) returns the string '€'. This is the inverse of ord().

The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base 16). ValueError will be raised if i is outside that range.

(二).大意

将一个整数i,转化成为Unicode代码的字符串。例如,chr(97)返回字符串'a',chr(8364)返回字符串'€'。是ord()的逆向操作。

参数的有效范围是0~1,114,111(基于16进制的0x10FFFF)。如果i超出该范围,则会引发ValueError异常。

(三).演示

 

 

@classmethod

(一).官方文档原文

Transform a method into a class method.

A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:

class C:
    @classmethod
    def f(cls, arg1, arg2, ...): ...

The @classmethod form is a function decorator – see Function definitions for details.

A class method can be called either on the class (such as C.f()) or on an instance (such as C().f()).

The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.

Class methods are different than C++ or Java static methods. If you want those, see staticmethod(). For more information on class methods, see The standard type hierarchy.

(二).大意

将一个方法转化成为类方法。类方法隐式地将类作为第一个参数,就像实例方法接收实例一样。@classmethod是一个函数装饰器。

可以在类(例如C.f())或实例(例如C().f())调用类方法。除了类之外,实例会被忽略。如果为派生类调用类方法,则派生类对象将作为第一个参数被隐式传递。

(三).演示

 

compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

(一).官方文档原文

Compile the source into a code or AST object. Code objects can be executed by exec() or eval(). source can either be a normal string, a byte string, or an AST object.

Refer to the ast module documentation for information on how to work with AST objects.

The filename argument should give the file from which the code was read; pass some recognizable value if it wasn’t read from a file ('<string>' is commonly used).

The mode argument specifies what kind of code must be compiled; it can be 'exec' if source consists of a sequence of statements, 'eval' if it consists of a single expression, or 'single' if it consists of a single interactive statement (in the latter case, expression statements that evaluate to something other than None will be printed).

The optional arguments flags and dont_inherit control which future statements 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().If the flags argument is given and dont_inherit is not (or is zero) then the future statements specified by the flags argument are used in addition to those that would be used anyway.If dont_inherit is a non-zero integer then the 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 attribute on the _Feature instance in the __future__ module.

The argument optimize specifies the optimization level of the compiler; the default value of -1 selects the optimization level of the interpreter as given by -O options.Explicit levels are 0 (no optimization; __debug__ is true), 1 (asserts are removed, __debug__ is false) or 2 (docstrings are removed too).

This function raises SyntaxError if the compiled source is invalid, and ValueError if the source contains null bytes. If you want to parse Python code into its AST representation, see ast.parse().

Note When compiling a string with multi-line code in 'single' or 'eval' mode, input must be terminated by at least one newline character. This is to facilitate detection of incomplete and complete statements in the code module.

Warning It is possible to crash the Python interpreter with a sufficiently large/complex string when compiling to an AST object due to stack depth limitations in Python’s AST compiler.

Changed in version 3.2: Allowed use of Windows and Mac newlines. Also input in 'exec' mode does not have to end in a newline anymore. Added the optimize parameter.

Changed in version 3.5: Previously, TypeError was raised when null bytes were encountered in source.

(二).大意

将源代码编译为代码或AST对象。代码对象可以被exec()或eval()执行。 source可以是普通字符串,字节字符串或AST对象。如何使用AST对象的信息,请参阅ast模块文档。

filename参数指定了代码从哪个文件中去读取;如果没有从文件中读取,则传递一些可识别的值(通常使用'<string>')。

mode参数指定哪几种代码需要被编译;如果source包含一系列语句,它可以是'exec';如果它由单个表达式组成,则为'eval';如果它由单个交互式语句组成,则为'single'(在后一种情况下,将打印计算为除None之外的其他内容的表达式语句)。

可选参数flags和dont_inherit控制将来的语句影响源的编译。 如果两者都不存在(或两者都为零),则使用在调用compile()的代码中生效的那些将来语句编译代码。如果给出flags参数且dont_inherit不是(或为零),那么除了将要使用的那些之外,还使用flags参数指定的future语句。如果dont_inherit是一个非零整数,那么flags参数就是它 - 忽略了对编译调用有效的未来语句。

将来的语句由位指定,这些位可以按位OR运算以指定多个语句。 指定给定特征所需的位域可以在__future__模块的_Feature实例上找到compiler_flag属性。

参数optimize指定编译器的优化级别; 默认值-1选择-O选项给出的解释器的优化级别。 显式级别为0(无优化; __debug__为真),1(断言被删除,__ debug__为假)或2(文档字符串也被删除)。

如果编译的源无效,则此函数引发SyntaxError;如果源包含空字节,则此函数引发ValueError。

如果要将Python代码解析为其AST表示,请参阅ast.parse()。

提示:在"single"或"eval"模式下编译具有多行代码的字符串时,输入必须至少由一个换行符终止。这有助于检测代码模块中不完整和完整的语句。

警告:由于Python的AST编译器中的堆栈深度限制,在编译为AST对象时,可能会使Python解释器崩溃并使用足够大/复杂的字符串。

3.2版本中已更改:允许使用Windows和Mac换行符。同样以'exec'模式输入也不必再以换行符结尾。添加了optimize参数。

3.5版本中已更改:以前,在源中遇到空字节时引发了TypeError。

(三).演示

 

class complex([real[, imag]])

(一).官方文档原文

Return a complex number with the value 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 constructor serves as a numeric conversion like int and float. If both arguments are omitted, returns 0j.

Note When converting from a string, the string must not contain whitespace around the central + or - operator. For example, complex('1+2j') is fine, but complex('1 + 2j') raises ValueError.

The complex type is described in Numeric Types — int, float, complex.

Changed in version 3.6: Grouping digits with underscores as in code literals is allowed.

(二).大意

返回real + imag * 1j的复数或将字符串、数字转换为复数。

如果第一个参数是一个字符串,它将被解释为一个复数,在调用该函数是不能有第二个参数。第二个参数永远不能是字符串。每个参数可以是任何数字类型(包括复数)。

如果省略imag,则默认为零,构造函数用作int和float之类的数字转换。如果省略两个参数,则返回0j。

注意:由字符串转换时,字符串中不得出现空格。例如,complex('1+2j')没有问题,但complex('1 + 2j')会引发ValueError异常。

3.6版本中已更改:允许使用下划线对数字进行分组。

(三).演示

 

delattr(object, name)

(一).官方文档原文

This is a relative of setattr(). The arguments are an object and a string. The string must be the name of one of the object's attributes. The function deletes the named attribute, provided the object allows it.

For example, delattr(x, 'foobar') is equivalent to del x.foobar.

(二).大意

setattr()的逆向操作。参数是一个对象和一个字符串。该字符串必须是对象属性的其中一个名称。如果对象允许,该函数将删除命名属性。

例如,delattr(x, 'foobar') 等价于 del x.foobar

(三).演示

 

class dict()、class dict(mapping, **kwarg)、class dict(iterable, **kwarg)

(一).官方文档原文

Create a new dictionary. The dict object is the dictionary class. See dict and Mapping Types — dict for documentation about this class.

For other containers see the built-in list, set, and tuple classes, as well as the collections module.

(二).大意

创建一个新的字典。dict对象是字典类。有关此类的文档,请参阅dict和Mapping Types - dict。对于其他容器,请参阅内置的list,set和tuple类以及collections模块。

(三).演示

 

dir([object])

(一).官方文档原文

Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.

If the object has a method named __dir__(), this method will be called and must return the list of attributes. This allows objects that implement a custom __getattr__() or __getattribute__() function to customize the way dir() reports their attributes.

If the object does not provide __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__().

The default 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.

The resulting list is sorted alphabetically. For example:

>>> 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']

Note Because 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.

(二).大意

如果没有参数,则返回当前本地范围中的名称列表。有参数,尝试返回一个该对象的有效属性的列表。

如果对象有名为__dir__()的方法,则将调用此方法,并且必须返回一个属性的列表。 这允许实现自定义__getattr__()或__getattribute__()函数的对象自定义dir()报告其属性的方式。

如果对象未提供__dir__(),dir()会尽力从对象的__dict__属性(如果已定义)及其类型对象中收集信息。结果不一定完整,并且当对象具有自定义__getattr__()时可能不准确。

默认的dir()机制对不同类型的对象表现不同,因为它尝试生成最相关的信息,而不是完整的信息:

如果对象是模块对象,则列表包含模块属性的名称。如果对象是类型或类对象,则列表包含其属性的名称,并且递归地包含其基础的属性。除此以外,列表包含对象的属性名称,其类的属性的名称,以及其类的基类的属性的递归。

注意:因为dir()主要是为了方便在交互式提示中使用而提供的,所以它尝试提供一组有趣的名称,而不是尝试提供严格或一致定义的名称集,并且其详细行为可能会在不同版本之间发生变化。 例如,当参数是类时,元类属性不在结果列表中。

(三).演示

 

divmod(a, b)

(一).官方文档原文

Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using integer division.With mixed operand types, the rules for binary arithmetic operators apply.

For integers, the result is the same as (a // b, a % b).For floating point numbers the result is (q, a % b), where q is usually math.floor(a / b) but may be 1 less than that. In any case q * b + a % b is very close to a, if a % b is non-zero it has the same sign as b, and 0 <= abs(a % b) < abs(b).

(二).大意

两个(非复数)数作为参数,返回商和余数组成的一对数字。 对于混合操作数类型,二进制算术运算符的规则适用。 对于整数,结果等价于(a // b,a%b)。 对于浮点数,结果等价于(q,a%b),其中q通常是math.floor(a / b),但可能比该值小1。 在任何情况下,q * b + a%b非常接近a,如果%b非零,则其具有与b相同的符号,并且0 <= abs(a%b)<abs(b)。

(三).演示

 

 

enumerate(iterable, start=0)

(一).官方文档原文

Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration.

The __next__() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.

>>> 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')]

Equivalent to:

def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1

(二).大意

返回一个枚举对象。 iterable必须是一个序列、一个迭代器或其他支持迭代的对象。enumerate()通过迭代器的__next__()方法返回一个元组,包含count(从start开始,默认为0)和迭代得到的值。

(三).演示

enumerate()实际上所返回的是一个迭代器

 

eval(expression, globals=None, locals=None)

(一).官方文档原文

The arguments are a string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object.

The expression 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 does not contain a value for the key __builtins__, a reference to the dictionary of the built-in module builtins is inserted under that key before expression is parsed. This means that expression normally has full access to the standard builtins 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
>>> 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' as the mode argument, eval()’s return value will be None.

Hints: dynamic execution of statements is supported by the exec() function. The globals() and locals() functions returns the current global and local dictionary, respectively, which may be useful to pass around for use by eval() or exec().

See ast.literal_eval() for a function that can safely evaluate strings with expressions containing only literals.

(二).大意

参数是一个字符串,可选参数为globals和locals。如果有,globals必须是字典,locals可以是任何映射对象。

expression参数将作为Python表达式(技术上讲,条件列表)被解析和评估,使用globals和locals字典作为全局和本地名称空间。如果globals字典存在且不包含键__builtins__的值,则在解析表达式之前,会在该键下插入对内置模块内置字典的引用。这意味着表达式通常具有对标准内置模块的完全访问权限,并且传播受限制的环境。如果省略locals字典,则默认为globals字典。如果省略两个字典,则表达式在调用eval()的环境中执行。返回值是计算表达式的结果。语法错误报告为异常。

此函数还可用于执行任意代码对象(例如由compile()创建的代码对象)。 在这种情况下,传递代码对象而不是字符串。如果代码对象已使用'exec'作为mode参数进行编译,则eval()的返回值将为None。

提示:exec()函数支持语句的动态执行。 globals()和locals()函数分别返回当前的全局和本地字典,这可能对传递以供eval()或exec()使用很有用。

有关可以使用仅包含文字的表达式安全地计算字符串的函数,请参阅ast.literal_eval()

(三).演示

 

exec(object[, globals[, locals]])

(一).官方文档原文

This function supports dynamic execution of Python code. object must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). If it is a code object, it is simply executed. In all cases, the code that’s executed is expected to be valid as file input (see the section “File input” in the Reference Manual). Be aware that the return and yield statements may not be used outside of function definitions even within the context of code passed to the exec() function. The return value is None.

In all cases, if the optional parts are omitted, the code is executed in the current scope. If only globals is provided, it must be a dictionary, which will be used for both the global and the local variables. If globals and locals are given, they are used for the global and local variables, respectively. If provided, locals can be any mapping object. Remember that at module level, globals and locals are the same dictionary. If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition.

If the globals dictionary does not contain a value for the key __builtins__, a reference to the dictionary of the built-in module builtins is inserted under that key. That way you can control what builtins are available to the executed code by inserting your own __builtins__ dictionary into globals before passing it to exec().

Note: The built-in functions globals() and locals() return the current global and local dictionary, respectively, which may be useful to pass around for use as the second and third argument to exec().

Note: The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.

(二).大意

此函数支持Python代码的动态执行。object参数必须是字符串或代码对象。如果它是一个字符串,则将该字符串解析为一组Python语句,然后执行该语句(除非发生语法错误)。如果它是代码对象,则只执行它。在所有情况下,执行的代码应该作为文件输入有效(请参见“参考手册”中的“文件输入”部分)。请注意,即使在传递给exec()函数的代码的上下文中,也不能在函数定义之外使用return和yield语句。返回值为None。

在所有情况下,如果省略可选部分,则代码在当前范围内执行。如果只提供globals变量,则它必须是字典,它将用于全局变量和局部变量。如果globals和locals都给了,则它们分别用于全局变量和局部变量。如果提供,则locals可以是任何映射对象。请记住,在模块级别,全局变量和本地变量是相同的字典。如果exec获得两个单独的对象作为全局变量和局部变量,则代码将被执行,就像它嵌入在类定义中一样。

如果全局字典不包含键__builtins__的值,则在该键下插入对内置模块内置字典的引用。 这样,通过将自己的__builtins__字典插入到globals中,然后将其传递给exec(),您可以控制执行代码可用的内置函数。

注意:内置函数globals()和locals()分别返回当前的全局和本地字典,这可能有助于传递用作exec()的第二个和第三个参数。

注意:默认的locals的行为与下面的函数locals()相同:不应尝试修改默认的locals字典。 如果您需要在函数exec()返回后查看代码对locals的影响,则传递显式的locals字典。

(三).演示

 

filter(function, iterable)

(一).官方文档原文

Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

Note that filter(function, iterable) is equivalent to the generator expression (item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is None.

See itertools.filterfalse() for the complementary function that returns elements of iterable for which function returns false.

(二).大意

取iterable中返回true的元素,最终构造成一个迭代器。iterable可以是序列、支持迭代的容器,也可以是迭代器。如果function为None,则假定为identity函数,即删除所有可迭代的false元素。

请注意,如果函数不是None,则filter(function,iterable)等效于生成器表达式(item for item in iterable if function(item)),如果function为None,则(item for item in iterable if item)

请参阅itertools.filterfalse()以获取补充函数,该函数返回函数返回false的iterable元素。

(三).演示

 

class float([x])

(一).官方文档原文

Return a floating point number constructed from a number or string x.

If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded in whitespace. The optional sign may be '+' or '-'; a '+' sign has no effect on the value produced. The argument may also be a string representing a NaN (not-a-number), or a positive or negative infinity. More precisely, the input must conform to the following grammar after leading and trailing whitespace characters are removed:

sign           ::=  "+" | "-"
infinity       ::=  "Infinity" | "inf"
nan            ::=  "nan"
numeric_value  ::=  floatnumber | infinity | nan
numeric_string ::=  [sign] numeric_value

Here floatnumber is the form of a Python floating-point literal, described in Floating point literals. Case is not significant, so, for example, “inf”, “Inf”, “INFINITY” and “iNfINity” are all acceptable spellings for positive infinity.

Otherwise, if the argument is an integer or a floating point number, a floating point number with the same value (within Python’s floating point precision) is returned. If the argument is outside the range of a Python float, an OverflowError will be raised.

For a general Python object x, float(x) delegates to x.__float__().

If no argument is given, 0.0 is returned.

Examples:

>>> float('+1.23')
1.23
>>> float('   -12345\n')
-12345.0
>>> float('1e-003')
0.001
>>> float('+1E6')
1000000.0
>>> float('-Infinity')
-inf

The float type is described in Numeric Types — int, float, complex.

Changed in version 3.6: Grouping digits with underscores as in code literals is allowed.

Changed in version 3.7: x is now a positional-only parameter.

(二).大意

返回由数字或字符串x构造的浮点数。

如果参数是一个字符串,它应该包含一个十进制数字,可选地以符号开头,并且可选地嵌入在空格中。 可选符号可以是“+”或“ - ”; “+”符号对产生的值没有影响。 参数也可以是表示NaN(非数字)或正或负无穷大的字符串。 更确切地说,在删除前导和尾随空格字符后,输入必须符合语法。

这里floatnumber是Python浮点文字的形式,在浮点文字中描述。案例并不重要,因此,例如:"inf","Inf","INFINITY"和"iNfINity"都是正无限的可接受拼写。

否则,如果参数是整数或浮点数,则返回具有相同值的浮点数(在Python的浮点精度内)。如果参数超出了Python float的范围,则会引发OverflowError。

对于一般Python对象x,float(x)委托给x.__float__()

float类型在Numeric Types中描述 - int,float,complex。

3.6版本中已更改:允许使用下划线对数字进行分组,如代码文字。

3.7版本中已更改:x现在是仅位置参数。

(三).演示

 

format(value[, format_spec])

(一).官方文档原文

Convert a value to a “formatted” representation, as controlled by format_spec. The interpretation of format_spec will depend on the type of the value argument, however there is a standard formatting syntax that is used by most built-in types: Format Specification Mini-Language.

The default format_spec is an empty string which usually gives the same effect as calling str(value).

A call to format(value, format_spec) is translated to type(value).__format__(value, format_spec) which bypasses the instance dictionary when searching for the value’s __format__() method. A TypeError exception is raised if the method search reaches object and the format_spec is non-empty, or if either the format_spec or the return value are not strings.

Changed in version 3.4: object().__format__(format_spec) raises TypeError if format_spec is not an empty string.

(二).大意

将值转换为“格式化”表示,由format_spec控制。 format_spec的解释取决于value参数的类型,但是大多数内置类型都使用标准格式化语法:Format Specification Mini-Language

默认的format_spec是一个空字符串,通常与调用str(value)具有相同的效果。

对format(value,format_spec)的调用被转换为type(value).__format__(value,format_spec),它在搜索值的__format__()方法时绕过实例字典。 如果方法搜索到达对象且format_spec为非空,或者format_spec或返回值不是字符串,则引发TypeError异常。

3.4版本中已更改:如果format_spec不是空字符串,则object().__format__(format_spec)引发TypeError。

(三).演示

 

class frozenset([iterable])

(一).官方文档原文

Return a new frozenset object, optionally with elements taken from iterable. frozenset is a built-in class. See frozenset and Set Types — set, frozenset for documentation about this class.

For other containers see the built-in set, list, tuple, and dict classes, as well as the collections module.

(二).大意

返回一个新的frozenset对象,可选地包含从iterable中获取的元素。frozenset是一个内置类。有关此类的文档,请参阅frozenset和Set Types - set,frozenset

对于其他容器,请参阅内置的set,list,tuple和dict类,以及collections模块。

(三).演示

 

getattr(object, name[, default])

(一).官方文档原文

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object's attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

(二).大意

返回object中,named属性的值。 name必须是一个字符串。如果字符串是对象属性之一的名称,则结果是该属性的值。例如,getattr(x,'foobar')等同于x.foobar。如果named属性不存在,则返回default(如果有提供),否则引发AttributeError。

(三).演示

 

globals()

(一).官方文档原文

Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).

(二).大意

返回表示当前全局符号表的字典。这始终是当前模块的字典(在函数或方法内部,这是定义它的模块,而不是调用它的模块)。

(三).演示

 

hasattr(object, name)

(一).官方文档原文

The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an AttributeError or not.)

(二).大意

参数是一个对象和一个字符串。如果字符串是对象属性之一的名称,则结果为True,否则返回False。(这是通过调用getattr(object,name)并查看它是否引发AttributeError来实现的)

(三).演示

 

hash(object)

(一).官方文档原文

Return the hash value of the object (if it has one). Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup. Numeric values that compare equal have the same hash value (even if they are of different types, as is the case for 1 and 1.0).

Note: For objects with custom __hash__() methods, note that hash() truncates the return value based on the bit width of the host machine. See __hash__() for details.

(二).大意

返回对象的哈希值(如果有的话)。哈希值是整数。它们用于在字典查找期间快速比较字典键。比较相等的数字值具有相同的哈希值(即使它们具有不同的类型,如1和1.0的情况)。

对于具有自定义__hash__()方法的对象,请注意hash()根据主机的位宽截断返回值。有关详细信息,请参阅__hash__()

(三).演示

 

 

help([object])

(一).官方文档原文

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.

Note that if a slash(/) appears in the parameter list of a function, when invoking help(), it means that the parameters prior to the slash are positional-only. For more info, see the FAQ entry on positional-only parameters.

This function is added to the built-in namespace by the site module.

Changed in version 3.4: Changes to pydoc and inspect mean that the reported signatures for callables are now more comprehensive and consistent.

(二).大意

调用内置帮助系统。(此函数用于交互式使用)如果未给出参数,则交互式帮助系统将在解释器控制台上启动。如果参数是字符串,则查找字符串作为模块,函数,类,方法,关键字或文档主题的名称,并在控制台上打印帮助页面。如果参数是任何其他类型的对象,则会生成对象的帮助页面。

请注意,如果函数的参数列表中出现斜杠(/),则在调用help()时,意味着斜杠之前的参数仅为位置参数。有关详细信息,请参阅有关仅位置参数的FAQ条目。

此功能由site模块添加到内置命名空间。

3.4版本中已更改:对pydoc和inspect的更改意味着报告的callables签名现在更加全面和一致。

(三).演示

 

hex(x)

(一).官方文档原文

Convert an integer number to a lowercase hexadecimal string prefixed with “0x”. If x is not a Python int object, it has to define an __index__() method that returns an integer. Some examples:

>>> hex(255)
'0xff'
>>> hex(-42)
'-0x2a'

If you want to convert an integer number to an uppercase or lower hexadecimal string with prefix or not, you can use either of the following ways:

>>> '%#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')

See also format() for more information.

See also int() for converting a hexadecimal string to an integer using a base of 16.

Note: To obtain a hexadecimal string representation for a float, use the float.hex() method.

(二).大意

将整数转换为带有前缀"0x"的小写十六进制字符串。如果x不是Python int对象,则必须定义一个返回整数的__index__()方法。

也可以将整数转换为带有前缀或不带前缀的大写或小写十六进制字符串。

有关更多信息,另请参见format()

参见int(),将十六进制字符串转换为使用16的基数的整数

注意:要获取float的十六进制字符串表示形式,请使用float.hex()方法。

(三).演示

 

id(object)

(一).官方文档原文

Return the "identity" of an object. This is an 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() value.

CPython implementation detail: This is the address of the object in memory.

(二).大意

返回对象的“标识”。这是一个整数,在该生命周期内保证该对象是唯一且恒定的。具有非重叠生存期的两个对象可以具有相同的id()值。

CPython实现细节:这是内存中对象的地址。

(三).演示

 

input([prompt])

(一).官方文档原文

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. Example:

>>> s = input('--> ')  
--> Monty Python's Flying Circus
>>> s  
"Monty Python's Flying Circus"

If the readline module was loaded, then input() will use it to provide elaborate line editing and history features.

(二).大意

如果存在prompt参数,则将其写入标准输出而不带尾随换行符。然后,该函数从输入中读取一行,将其转换为字符串(剥离尾部换行符),然后返回该行。读取EOF时,会引发EOFError异常。

如果加载了readline模块,则input()将使用它来提供精细的行编辑和历史记录功能。

(三).演示

 

class int()、class int(x, base=10)

(一).官方文档原文

Return an integer object constructed from a number or string x, or return 0 if no arguments are given. If x defines __int__(), int(x) returns x.__int__(). If x defines __trunc__(), it returns x.__trunc__(). For floating point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in radix base. Optionally, the literal can be preceded by + or - (with no space in between) and surrounded by whitespace. A base-n literal consists of the digits 0 to n-1, with a to z (or A to Z) having values 10 to 35. The default base is 10. The allowed values are 0 and 2–36. Base-2, -8, and -16 literals can be optionally prefixed with 0b/0B, 0o/0O, or 0x/0X, as with integer literals in code. Base 0 means to interpret exactly as a code literal, so that the actual base is 2, 8, 10, or 16, and so that int('010', 0) is not legal, while int('010') is, as well as int('010', 8).

The integer type is described in Numeric Types — int, float, complex.

Changed in version 3.4: If base is not an instance of int and the base object has a base.__index__ method, that method is called to obtain an integer for the base. Previous versions used base.__int__ instead of base.__index__.

Changed in version 3.6: Grouping digits with underscores as in code literals is allowed.

Changed in version 3.7: x is now a positional-only parameter.

(二).大意

返回由数字或字符串x构造的整数对象,如果没有给出参数,则返回0。如果x定义__int__(),则int(x)返回x.__int__()。如果x定义__trunc__(),则返回x.__trunc__()。对于浮点数,这会截断为零。

如果x不是数字或者给定了base,则x必须是字符串,字节或bytearray实例,表示以radix为基数的整数文字。可选地,文字可以在前面加+或-(之间没有空格)并且用空格包围。base-n文字由数字0到n-1组成,a到z(或A到Z)的值为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(object, classinfo)

(一).官方文档原文

Return true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. If object is not an object of the given type, the function always returns false. If classinfo is a tuple of type objects (or recursively, other such tuples), return true if object is an instance of any of the types. If classinfo is not a type or tuple of types and such tuples, a TypeError exception is raised.

(二).大意

如果object参数是classinfo参数的实例,或者是(直接,间接或虚拟)子类的实例,则返回true。如果object不是给定类型的对象,则该函数始终返回false。如果classinfo是类型对象的元组(或递归,其他此类元组),如果object是任何类型的实例,则返回true。如果classinfo不是类型和元组的类型或元组,则会引发TypeError异常。

(三).演示

 

issubclass(class, classinfo)

(一).官方文档原文

Return true if class is a subclass (direct, indirect or virtual) of classinfo. A class is considered a subclass of itself. classinfo may be a tuple of class objects, in which case every entry in classinfo will be checked. In any other case, a TypeError exception is raised.

(二).大意

如果class是classinfo的子类(直接,间接或虚拟),则返回true。类被认为是其自身的子类。classinfo可以是类对象的元组,在这种情况下,将检查classinfo中的每个条目。在任何其他情况下,都会引发TypeError异常。

(三).演示

 

iter(object[, sentinel])

(一).官方文档原文

Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, object must be a collection object which supports the iteration protocol (the __iter__() method), or it must support the sequence protocol (the __getitem__() method with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised. If the second argument, sentinel, is given, then object must be a callable object. The iterator created in this case will call object with no arguments for each call to its __next__() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.

See also Iterator Types.

One useful application of the second form of iter() is to build a block-reader. For example, reading fixed-width blocks from a binary database file until the end of file is reached:

from functools import partial
with open('mydata.db', 'rb') as f:
    for block in iter(partial(f.read, 64), b''):
        process_block(block)

(二).大意

返回一个迭代器对象。根据第二个参数的存在,第一个参数的解释非常不同。如果没有第二个参数,object必须是支持迭代协议(__iter__()方法)的集合对象,或者它必须支持序列协议(__getitem__()方法,其整数参数从0开始)。如果它不支持这些协议中的任何一个,则引发TypeError。如果给出第二个参数sentinel,则object必须是可调用对象。在这种情况下创建的迭代器将为每个对__next__()方法的调用调用没有参数的对象;如果返回的值等于sentinel,则会引发StopIteration,否则返回该值。

另请参见迭代器类型。

第二种形式的iter()的一个有用的应用是构建一个块读取器。例如,从二进制数据库文件中读取固定宽度的块,直到达到文件末尾。

(三).演示

 

len(s)

(一).官方文档原文

Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

(二).大意

返回对象的长度(项目数)。参数可以是序列(例如字符串,字节,元组,列表或范围)或集合(例如字典,集合或冻结集)。

(三).演示

 

class list([iterable])

(一).官方文档原文

Rather than being a function, list is actually a mutable sequence type, as documented in Lists and Sequence Types — list, tuple, range.

(二).大意

list实际上是一个可变序列类型,而不是一个函数,如列表和序列类型中所述 - 列表,元组,范围。

(三).演示

 

locals()

(一).官方文档原文

Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks. Note that at the module level, locals() and globals() are the same dictionary.

Note: The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

(二).大意

更新并返回表示当前本地符号表的字典。locals()在函数块中调用时返回自由变量,但在类块中不调用。请注意,在模块级别,locals()和globals()是相同的字典。

注意:不应修改此词典的内容;更改可能不会影响解释器使用的本地和自由变量的值。

(三).演示

 

map(function, iterable, ...)

(一).官方文档原文

Return an iterator that applies function to every item of iterable, yielding the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see itertools.starmap().

(二).大意

返回一个迭代器,它将函数应用于每个iterable项,从而产生结果。如果传递了其他可迭代参数,则函数必须采用那么多参数,并且并行地应用于所有迭代的项。对于多个迭代,迭代器在最短的iterable耗尽时停止。对于函数输入已经排列成参数元组的情况,请参阅itertools.starmap()

(三).演示

 

max(iterable, *[, key, default])、max(arg1, arg2, *args[, key])

(一).官方文档原文

Return the largest item in an iterable or the largest of two or more arguments.

If one positional argument is provided, it should be an iterable. The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned.

There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for list.sort(). The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised.

If multiple items are maximal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as sorted(iterable, key=keyfunc, reverse=True)[0] and heapq.nlargest(1, iterable, key=keyfunc).

New in version 3.4: The default keyword-only argument.

(二).大意

返回一个可迭代对象(或两个及更多属性)中,最大的项。

如果提供了一个位置参数,则它应该是可迭代的。返回iterable中的最大项。如果提供了两个或多个位置参数,则返回最大的位置参数。

有两个可选的关键字限定参数。key参数指定一个单参数排序函数,就像list.sort()一样。 如果提供的iterable为空,则default参数指定要返回的对象。如果iterable为空并且未提供default,则引发ValueError异常。

如果有多个项是最大的,则该函数返回遇到的第一个项。这与其他排序稳定性保留工具一致,例如sorted(iterable,key=keyfunc,reverse=True)[0]和heapq.nlargest(1,iterable,key=keyfunc)

3.4版本中新特性:default为关键字限定参数。

(三).演示

 

memoryview(obj)

(一).官方文档原文

Return a "memory view" object created from the given argument. See Memory Views for more information.

(二).大意

返回从给定参数创建的“内存视图”对象。 有关更多信息,请参阅内存视图

(三).演示

 

 

min(iterable, *[, key, default])、min(arg1, arg2, *args[, key])

(一).官方文档原文

Return the smallest item in an iterable or the smallest of two or more arguments.

If one positional argument is provided, it should be an iterable. The smallest item in the iterable is returned. If two or more positional arguments are provided, the smallest of the positional arguments is returned.

There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for list.sort(). The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised.

If multiple items are minimal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as sorted(iterable, key=keyfunc)[0] and heapq.nsmallest(1, iterable, key=keyfunc).

New in version 3.4: The default keyword-only argument.

(二).大意

返回一个可迭代对象(或两个及更多属性)中,最小的项。

如果提供了一个位置参数,则它应该是可迭代的。返回iterable中的最小项。如果提供了两个或多个位置参数,则返回最小的位置参数。

有两个可选的关键字限定参数。key参数指定一个单参数排序函数,就像list.sort()一样。如果提供的iterable为空,则default参数指定要返回的对象。如果iterable为空并且未提供default,则引发ValueError异常。

如果有多个项是最小的,则该函数返回遇到的第一个项。这与其他排序稳定性保留工具一致,例如sorted(iterable,key=keyfunc,reverse=True)[0]和heapq.nlargest(1,iterable,key=keyfunc)

3.4版本中新特性:default为关键字限定参数。

(三).演示

max()的对立函数,max()取最大,min()取最小

 

next(iterator[, default])

(一).官方文档原文

Retrieve the next item from the iterator by calling its __next__() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.

(二).大意

通过调用__next__()方法从迭代器中检索下一个项。如果给定default,则在迭代器耗尽时返回,否则引发StopIteration异常。

(三).演示

 

class object

(一).官方文档原文

Return a new featureless object. object is a base for all classes. It has the methods that are common to all instances of Python classes. This function does not accept any arguments.

Note: object does not have a __dict__, so you can't assign arbitrary attributes to an instance of the object class.

(二).大意

返回一个新的无特征对象。 object是所有类的基类。它具有所有Python类实例共有的方法。此函数不接受任何参数。

object没有__dict__,因此你无法将任意属性分配给object类的实例。

(三).演示

 

oct(x)

(一).官方文档原文

Convert an integer number to an octal string prefixed with “0o”. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer. For example:

>>> oct(8)
'0o10'
>>> oct(-56)
'-0o70'

If you want to convert an integer number to octal string either with prefix “0o” or not, you can use either of the following ways.

>>> '%#o' % 10, '%o' % 10
('0o12', '12')
>>> format(10, '#o'), format(10, 'o')
('0o12', '12')
>>> f'{10:#o}', f'{10:o}'
('0o12', '12')

See also format() for more information.

(二).大意

将整数转换成以"0o"前缀的八进制字符串。结果是一个有效的Python表达式。如果x不是Python int对象,则必须定义一个返回整数的__index__()方法。

如果要将整数转换为带有前缀"0o"的八进制字符串,可以使用以下任一方法。

有关更多信息,另请参见format()

(三).演示

 

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

(一).官方文档原文

Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised.

file is a path-like object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False.)

mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode. Other common values are 'w' for writing (truncating the file if it already exists), 'x' for exclusive creation and 'a' for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position). In text mode, if encoding is not specified the encoding used is platform dependent: locale.getpreferredencoding(False) is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave encoding unspecified.) The available modes are:

The default mode is 'r' (open for reading text, synonym of 'rt'). For binary read-write access, the mode 'w+b' opens and truncates the file to 0 bytes. 'r+b' opens the file without truncation.

As mentioned in the Overview, Python distinguishes between binary and text I/O. Files opened in binary mode (including 'b' in the mode argument) return contents as bytes objects without any decoding. In text mode (the default, or when 't' is included in the mode argument), the contents of the file are returned as str, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given.

There is an additional mode character permitted, 'U', which no longer has any effect, and is considered deprecated. It previously enabled universal newlines in text mode, which became the default behaviour in Python 3.0. Refer to the documentation of the newline parameter for further details.

Note: Python doesn't depend on the underlying operating system’s notion of text files; all the processing is done by Python itself, and is therefore platform-independent.

buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size in bytes of a fixed-size chunk buffer. When no buffering argument is given, the default buffering policy works as follows:

·Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device's "block size" and falling back on io.DEFAULT_BUFFER_SIZE. On many systems, the buffer will typically be 4096 or 8192 bytes long.

·"Interactive" text files (files for which isatty() returns True) use line buffering. Other text files use the policy described above for binary files.

encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever locale.getpreferredencoding() returns), but any text encoding supported by Python can be used. See the codecs module for the list of supported encodings.

errors is an optional string that specifies how encoding and decoding errors are to be handled—this cannot be used in binary mode. A variety of standard error handlers are available (listed under Error Handlers), though any error handling name that has been registered with codecs.register_error() is also valid. The standard names include:

·'strict' to raise a ValueError exception if there is an encoding error. The default value of None has the same effect.

·'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 the surrogateescape 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 be True (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 passing None).

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. When open() is used to open a file in a text mode ('w', 'r', 'wt', 'rt', etc.), it returns a subclass of io.TextIOBase (specifically io.TextIOWrapper). When used to open a file in a binary mode with buffering, the returned class is a subclass of io.BufferedIOBase. The exact class varies: in read binary mode, it returns an io.BufferedReader; in write binary and append binary modes, it returns an io.BufferedWriter, and in read/write mode, it returns an io.BufferedRandom. When buffering is disabled, the raw stream, a subclass of io.RawIOBase, io.FileIO, is returned.

See also the file handling modules, such as, fileinput, io (where open() is declared), os, os.path, tempfile, and shutil.

Changed in version 3.3:

·The opener parameter was added.

·The 'x' mode was added.

·IOError used to be raised, it is now an alias of OSError.

·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 475 for 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 than io.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 integer 97 and ord('€') (Euro sign) returns 8364. This is the inverse of chr().

(二).大意

给定表示一个Unicode字符的字符串,返回表示该字符的Unicode代码点的整数。例如,ord('a')返回整数97,ord('€')(欧元符号)返回8364.这是chr()的反转。

(三).演示

 

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 form pow(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 returns 100, but 10**-2 returns 0.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.

(二).大意

返回x的y次幂;如果z存在,则将x返回到幂y,模z(比pow(x,y)%z更有效地计算)。两个参数形式pow(x,y)相当于使用幂运算符:x**y

参数必须是数字类型。对于混合操作数类型,二进制算术运算符的强制规则适用。对于int操作数,结果与操作数具有相同的类型(在强制之后),除非第二个参数是否定的;在这种情况下,所有参数都转换为float并传递float结果。例如,10**2返回100,但10**-2返回0.01。如果第二个参数为负数,则必须省略第三个参数。如果存在z,则x和y必须是整数类型,y必须是非负的。

(三).演示

 

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 sep and 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, print() will just write end.

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.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.

(二).大意

将对象打印到文本流文件,以sep分隔,然后结束。sep,end,file和flush(如果存在)必须作为关键字参数给出。

所有非关键字参数都转换为字符串,如str(),并写入流,由sep分隔,后跟end。sep和end都必须是字符串; 它们也可以是None,这意味着使用默认值。如果没有给出对象,print()将只写入结束。

file参数必须是带有write(string)方法的对象;如果它不存在或None,将使用sys.stdout。由于打印的参数转换为文本字符串,因此print()不能与二进制模式文件对象一起使用。对于这些,请改用file.write(...)

输出是否缓冲通常由文件确定,但如果flush关键字参数为true,则强制刷新流。

3.3版本中已更改:增加了flush关键词参数。

(三).演示

 

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 and del 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 the voltage() 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, and deleter 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, and fdel 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.

(二).大意

range对象实际上是一个不可变的序列类型,而不是一个函数,如范围和序列类型 - 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.

(二).大意

返回包含对象的可打印表示的字符串。 对于许多类型,此函数尝试返回一个字符串,该字符串在传递给eval()时会产生具有相同值的对象,否则表示形式是一个用尖括号括起来的字符串,它包含对象类型的名称 附加信息通常包括对象的名称和地址。类可以通过定义__repr__()方法来控制此函数为其实例返回的内容。

(三).演示

 

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 at 0).

(二).大意

返回反向迭代器。seq必须是具有__reversed__()方法的对象,或者支持序列协议(__len__()方法和__getitem__()方法,整数参数从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 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, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). Any integer value is valid for ndigits (positive, zero, or negative). The return value is an integer if ndigits is omitted or None. Otherwise the return value has the same type as number.

For a general Python object number, round delegates to number.__round__.

Note The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.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.

(二).大意

返回数字四舍五入到小数点后的ndigits精度。如果省略ndigits或者为None,则返回其输入的最接近的整数。

对于支持round()的内置类型,将值四舍五入为函数减去ndigits的最接近的10的倍数; 如果两个倍数相等,则向均匀选择进行舍入(例如,圆形(0.5)和圆形(-0.5)都是0,圆形(1.5)是2)。任何整数值对ndigits(正数,零或负数)有效。如果省略ndigits或None,则返回值为整数。否则返回值与数字的类型相同。

对于一般的Python对象编号,将代理舍入为 number.__ round__

round()对于浮点数的行为可能会令人惊讶:例如,round(2.675,2)给出2.67而不是预期的2.68。这不是一个错误:这是因为大多数小数部分不能完全表示为浮点数。有关详细信息,请参阅浮点运算:问题和限制。

(三).演示

 

class set([iterable])

(一).官方文档原文

Return a new set object, optionally with elements taken from iterable. set is a built-in class. See set and Set Types — set, frozenset for documentation about this class.

For other containers see the built-in frozenset, list, tuple, and dict classes, as well as the collections module.

(二).大意

返回一个新的set对象,可选择使用可迭代的元素。set是一个内置类。有关此类的文档,请参阅set和Set Types - set,frozenset。

对于其他容器,请参阅内置的freezeset,list,tuple和dict类,以及collections模块。

(三).演示

 

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 to x.foobar = 123.

(二).大意

getattr()的对应操作。参数是一个对象,一个字符串和一个任意值。该字符串可以命名现有属性或新属性。如果对象允许,该函数会将值分配给属性。例如,setattr(x,'foobar',123)等效于x.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 step arguments default to None. Slice objects have read-only data attributes start, stop and step 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] or a[start:stop, i]. See itertools.islice() for an alternate version that returns an iterator.

(二).大意

返回一个切片对象,表示由range(start,stop,step)指定的索引集。start和step参数默认为None。切片对象具有只读数据属性start,stop和step,它们只返回参数值(或它们的默认值)。他们没有其他明确的功能; 但是它们被Numerical Python和其他第三方扩展使用。使用扩展索引语法时也会生成切片对象。例如:a[start:stop:step]或a[start:stop,i]。 有关返回迭代器的备用版本,请参阅itertools.islice()

(三).演示

 

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 is None (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.

(二).大意

从iterable中的项返回一个新的排序列表。

有两个可选参数,必须指定为关键字参数。

key指定一个参数的函数,该函数用于从iterable中的每个元素中提取比较键(例如,key=str.lower)。默认值为None(直接比较元素)。

reverse是一个布尔值。如果设置为True,则列表元素将按照每个比较相反的方式进行排序。

使用functools.cmp_to_key()将旧式cmp函数转换为键函数。

内置的sorted()函数保证稳定。如果排序保证不更改比较相等的元素的相对顺序,则排序是稳定的 - 这有助于在多个过程中进行排序(例如,按部门排序,然后按工资等级排序)。

有关排序示例和简要排序教程,请参阅排序方式。

(三).演示

 

@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 as C().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.

(二).大意

将方法转换为静态方法。

静态方法不会接收隐式的第一个参数。要声明静态方法,请使用此惯用语。

@staticmethod表单是一个函数装饰器 - 有关详细信息,请参阅函数定义。

可以在类(例如C.f())或实例(例如C().f())上调用静态方法。

Python中的静态方法与Java或C++中的静态方法类似。另请参阅classmethod()以获取对创建备用类构造函数有用的变体。

像所有装饰器一样,也可以将staticmethod称为常规函数,并对其结果执行某些操作。在某些需要从类主体引用函数并且您希望避免自动转换为实例方法的情况下,这是必需的。对于这些情况,请使用此习语。

有关静态方法的详细信息,请参阅标准类型层次结构。

(三).演示

 

class str(object='')、class str(object=b'', encoding='utf-8', errors='strict')

(一).官方文档原文

Return a str version of object. See str() for details.

str is the built-in string class. For general information about strings, see Text Sequence Type — str.

(二).大意

返回str版本或对象。有关详细信息,请参阅str()

str是内置的字符串类。有关字符串的一般信息,请参阅文本序列类型 - 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, see math.fsum(). To concatenate a series of iterables, consider using itertools.chain().

(二).大意

Sums从左到右开始和可迭代的项目并返回总数。 start默认为0. iterable的项通常是数字,起始值不允许是字符串。

对于某些用例,sum()有很好的替代方法。 连接字符串序列的首选快速方法是调用"".join(sequence) 要以扩展精度添加浮点值,请参阅math.fsum()。要连接一系列迭代,请考虑使用itertools.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 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) 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 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].

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.

(二).大意

元组实际上是一个不可变的序列类型,而不是一个函数,如元组和序列类型 - 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 identical type 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 override type.__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 a types.MappingProxyType to prevent direct dictionary updates).

Without an argument, vars() acts like locals(). 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 iterator n times so that each output tuple has the result of n 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, use itertools.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 the builtins module and assigning to builtins.__import__) in order to change semantics of the import 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 of importlib.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 the import 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] Note that the parser only accepts the Unix-style end of line convention. If you are reading the code from a file, make sure to use newline conversion mode to convert Windows or Mac-style newlines.

请注意,解析器只接受Unix风格的行尾约定。如果您正在从文件中读取代码,请确保使用换行转换模式来转换Windows或Mac样式的换行符。

 

posted @ 2019-04-17 15:56  root01_barry  阅读(994)  评论(0编辑  收藏  举报