从头学Python(二)

(11) 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). ValueErrorwill be raised if i is outside that range.

返回一个将一个unicode编码的整数表示成字符串。例如...。chr()是ord()的逆过程。其中参数i的范围大小是1114111(0x10FFFF 16进制),如果i超过这个值就会报错。

测试范例

(12) 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:

官方范例

The @classmethod form is a function decorator – see the description of function definitions in Function definitions for details.

It 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() in this section.

For more information on class methods, consult the documentation on the standard type hierarchy in The standard type hierarchy.

将一个方法变成一个类方法

一个类方法的第一个参数需要是表示自身类的 cls 参数,就像实例方法一样。

@classmethod是一个装饰器方法,如果想了解更多装饰器方法定义的细节请出门左转...(右键,新链接打开)

测试范例

(13) compile(sourcefilenamemodeflags=0dont_inherit=Falseoptimize=-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 ('' is commonly used).

The mode argument specifies what kind of code must be compiled; it can be 'exec' if sourceconsists 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 flagsargument 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_flagattribute on the _Feature instance in the __future__ module.

The argument optimize specifies the optimization level of the compiler; the default value of -1selects 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可以是普通字符串,byte字符串或AST对象。有关如何使用AST对象的信息,请参阅AST模块文档。

filename这个参数需要传递一些可以被代码所识别的字符串

mode参数必须编指定译哪种代码;如果source包含一系列语句,则可以是'exec',如果它由单个表达式组成,则为'eval';如果由单个交互式语句组成,则为'single'(在后一种情况下,表达式语句评估为某个除了无以外将被打印)指定编译哪种代码;如果source包含一系列语句,则可以是'exec',如果它由单个表达式组成,则为'eval';如果由单个交互式语句组成,则为'single'(在后一种情况下,表达式语句评估为某个除了无以外将被打印)

(14)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 % bis 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 基本相等;如果 a % b 非零,它的符号和 b 一样,并且 0 <= abs(a % b) < abs(b) (后半部分是搬过来的,总之就是除法的功能)

(15)dir()

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.

太长了,dir实际上就是__dir__,如果不传参数,就最大限度的去寻找本地作用域内包含的方法,如果传入一个带有__dir__方法的对象,这个方法就会返回__dir__内定义的属性,如果没有该方法,就会自己去寻找。下面是中文文档的翻译:

如果没有实参,则返回当前本地作用域中的名称列表。如果有实参,它会尝试返回该对象的有效属性列表。

如果对象有一个名为 __dir__() 的方法,那么该方法将被调用,并且必须返回一个属性列表。这允许实现自定义 __getattr__() 或 __getattribute__() 函数的对象能够自定义 dir() 来报告它们的属性。

如果对象不提供 __dir__(),这个函数会尝试从对象已定义的 __dict__ 属性和类型对象收集信息。结果列表并不总是完整的,如果对象有自定义 __getattr__(),那结果可能不准确。

默认的 dir() 机制对不同类型的对象行为不同,它会试图返回最相关而不是最全的信息:

如果对象是模块对象,则列表包含模块的属性名称。

如果对象是类型或类对象,则列表包含它们的属性名称,并且递归查找所有基类的属性。

否则,列表包含对象的属性名称,它的类属性名称,并且递归查找它的类的所有基类的属性。


测试范例

(16)enumerate(iterablestart=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.

枚举类型,输入一个可迭代对象,返回一个可迭代对象,可选参数start默认为0,即从第0位开始输出。

(17)eval(xpressionglobals=Nonelocals=None)

The arguments are a string and optional globals and locals. If provided, globalsmust 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 localsdictionary 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. 

输入的第一个参数是一个string类型的python表达式,相当于将一个字符串内数据解析成python脚本,所以传入的参数必须符合python语法规则才能执行,global必须是一个字典,locals可以是任何映射对象(例如zip())。

(18)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). [1] 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 theexec() 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, localscan 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().

(解释来源:中文文档)

这个函数支持动态执行 Python 代码。object 必须是字符串或者代码对象。如果是字符串,那么该字符串将被解析为一系列 Python 语句并执行(除非发生语法错误)。[1] 如果是代码对象,它将被直接执行。在任何情况下,被执行的代码都需要和文件输入一样是有效的(见参考手册中关于文件输入的章节)。请注意即使在传递给 exec() 函数的代码的上下文中,return 和 yield 语句也不能在函数定义之外使用。该函数返回值是 None 。

无论哪种情况,如果省略了可选参数,代码将在当前范围内执行。如果提供了 globals参数,就必须是字典类型,而且会被用作全局和本地变量。如果同时提供了 globals 和 locals 参数,它们分别被用作全局和本地变量。如果提供了 locals 参数,则它可以是任何映射型的对象。请记住在模块层级,全局和本地变量是相同的字典。如果 exec 有两个不同的 globals 和 locals 对象,代码就像嵌入在类定义中一样执行。

如果 globals 字典不包含 __builtins__ 键值,则将为该键插入对内建 builtins 模块字典的引用。因此,在将执行的代码传递给 exec() 之前,可以通过将自己的 __builtins__ 字典插入到 globals 中来控制可以使用哪些内置代码。


测试范例

(19)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 中函数 function 返回真的那些元素,构建一个新的迭代器。iterable 可以是一个序列,一个支持迭代的容器,或一个迭代器。如果 function 是 None ,则会假设它是一个身份函数,即 iterable 中所有返回假的元素会被移除。

请注意, filter(function, iterable) 相当于一个生成器表达式,当 function 不是 None 的时候为 (item for item in iterable if function(item));function 是 None 的时候为 (item for item in iterable if item) 。

请参阅 itertools.filterfalse() 了解,只有 function 返回 false 时才选取 iterable 中元素的补充函数。

这个方法比较常用,用于过滤掉一些数据集内不符合条件的数据。

测试范例

(20)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:

返回从数字或字符串 x 生成的浮点数。

如果实参是字符串,则它必须是包含十进制数字的字符串,字符串前面可以有符号,之前也可以有空格。可选的符号有 '+' 和 '-' ; '+' 对创建的值没有影响。实参也可以是 NaN(非数字)、正负无穷大的字符串。确切地说,除去首尾的空格后,输入必须遵循以下语法:

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.

这里, floatnumber 是 Python 浮点数的字符串形式,详见 浮点数字面值。字母大小写都可以,例如,“inf”、“Inf”、“INFINITY”、“iNfINity” 都可以表示正无穷大。

另一方面,如果实参是整数或浮点数,则返回具有相同值(在 Python 浮点精度范围内)的浮点数。如果实参在 Python 浮点精度范围外,则会触发 OverflowError。

对于一般的 Python 对象 x , float(x) 指派给 x.__float__() 。

如果没有实参,则返回 0.0 。

测试范例

你可能感兴趣的:(从头学Python(二))