自行翻译,水平有限,有许多不足,Document未解释到的地方,请用help()功能查询更详细解释
转载注明出处
目录
A
abs(x):转化为绝对值
all(iterable):判断可迭代对象的每个元素是否都为True值
any(iterable):判断可迭代对象的元素是否都为True值
ascii(object):返回一个对象可打印表示的字符串
B
bin(x):整数转化为二进制
bool([x]):转化为布尔值
bytearray:转化为可改变的字节数组
bytes:转化为不可改变的字节数组
C
callable(object):检测对象是否可被调用
chr(i):返回整数所对应的Unicode字符
classmethod(function):类方法的装饰器
compile:将字符串编译为代码
complex:转化为复数
D
delattr:删除对象的属性
dict:创建一个字典
dir:返回当前窗口内或类的属性
divmod:求商和余数
E
F
filter:
float:转化为一个浮点数
format:
frozenset:
正文
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.
返回一个数的绝对值。输入的参数可以是一个整数或一个浮点数。如果这个参数是复数,那么将返回它的模。(注:返回的模是浮点数)
1 | abs(1) |
all(iterable)
Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:
如果可迭代对象中所有的元素为Ture(或可迭代对象为空),那么返回Ture,它等价于:
1 | def all(iterable): |
例子:
1 | all([1,2]) |
any(iterable)
Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:
如果可迭代对象中任意一个元素为Ture,那么返回Ture。如果可迭代对象为空,则返回False,它等价于:
1 | def any(iterable): |
例子:
1 | any([0,1,2]) |
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. This generates a string similar to that returned by repr() in Python 2.
如同repr(),返回一个对象可打印表示的字符串,以\x,\u或者\U的ASCII码返回。但是repr()会忽视非ASCII码。产生的字符串与Python 2中的repr()所返回的类似。
1 | ascii('滑天下之大稽') |
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. Some examples:
将一个整数转化为以“0b”做前缀的二进制字符串,返回的结果是一个有效的Python表达式。如果x不是Python中的整数对象,那么它必须定义一个__index__()且为整数。一些例子:
1 | bin(3) |
或者定义一个__index__()且为整数
1 | class C: |
If prefix “0b” is desired or not, you can use either of the following ways.
可用下列方法保留或舍去前缀“0b”:
1 | format(14, '#b'), format(14, 'b') |
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).
返回一个True或False的布尔值,x通过标准真值测试过程被转化。如果x是false或是缺省,会返回False,否则返回True。布尔值类型是整数类型的一个子类,并且不能再细分,它仅有False和True。
1 | bool(True) |
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.
返回一个新的字节数组,字节数组类是一组范围在[0,256)内的可变整数序列,它有着大多数可变序列和字节类的用法。使用这些不同的方法,可选的参数源可被用来初始化数组。
如果是字符串,你必须也要给出它的编码,通过使用str.encode(),可以使得字符串转化为字节。
1 | bytearray('中国','utf-8') |
如果是一个整数,数组将会有同等大小,并被初始为空字节数组。
1 | bytearray(3) |
如果是向缓冲接口证实过的对象,对象的只读缓冲将被用来初始数组。(注:测试后发现只要参数是bytes型的,直接返回)
如果是一个可迭代对象,它必须是[0,256)内的整数,用来做数组的初始内容
1 | bytearray([1,2,3,4,5]) |
如果没有输入参数,会建立一个长度为0字节数组
1 | bytearray() b = |
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.
返回一个新的字节数组对象,它是一个不可改变的范围在[0,256)的整数序列,bytes是不可改变的bytearray版本。
1 | bytes() b = |
操作同bytearray,但是bytes不可改变。
返回顶部
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,可调用的对象有可能返回False,但是不可调用的对象绝不会返回True。类对象是可调用对象,实例是否可以调用,取决于是否定义了__call__方法。
1 | class A: #类A是可调用对象,但实例a是不可调用对象 |
chr(i)
chr(i)
Return the string representing a character whose Unicode code point is the integer i. For example, chr(97) returns the string ‘a’. 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字符的字符串,是ord()的逆操作,整数i的范围是[0,1114111],16进制表示为0x10FFFF。
1 | chr(22) |
classmethod(function)
Return a class method for function.
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 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。
1 | class C: |
@classmethod 格式是一种修饰器,来看到功能定义中功能定义的细节描述。它既可以是C.f(),被类对象调用,也可以是C().f(),被类的实例对象调用。除了类之外,实例被忽略。如果一个类方法被称为派生类,那么派生类对象会传递第一个内含参数。
类方法不同于C++和Java中的静态方法。
1 | class C: |
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 (‘
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 (see PEP 236) affect the compilation of source. If neither is present (or both are zero) the code is compiled with those future statements that are in effect in the code that is calling compile(). 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().
把源代码编译成代码或AST对象,代码可以被exec()或eval()执行。源代码可以是普通字符串,也可以是字节串,或是AST对象。参考AST模块文档,来了解AST对象是如何工作的。
输入的文件名应当指导文件从哪儿读取代码。如果不读取文件,应当给予一些可辨认的值。(注:不读取文件,filename是空字符即可。)
输入的参数应清晰地指出那种代码需要编译。可以是‘exec’,当参数是一系列的声明时;也可以是‘eval’,当参数包含简单的表达式;也可以是’single’,当参数包含了简单的交互式命令。
(注:statement 声明,expression 表达式)
引用于知乎:
Expression是有值的。一个函数调用(Function Call)是一个表达式,一个普通的运算。
Statement是没有值的。一个函数定义(Function Definition)是一个声明,一个赋值语句是一个声明。
expression : 是什么
比如: 1+2是3, 1+2就是expression, 3 就是expression的 value
statement: 做什么
比如: a = 1, 把 a 绑定到整数1上, 并没有什么value 返回, 只是一个动作而已。
例子:
1 | 'for i in range(0,5): print (i)' #一系列的声明 code1 = |
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.
返回一个值为型为 a+bj 的复数或把字符串或数字转化为复数。如果第一个输入参数为字符串,那么字符串会被理解为一个复数,并且不需要第二个输入参数。第二个输入参数不能是字符串。每一个输入参数都可以是任何形式的数(包括复数)。如果复数的虚部缺省,那么生成器将会把它当作整数或浮点数看待;如果实部和虚部都缺省,那么返回0j。
注意,如果使用字符串来表示复数,那么连接实部和虚部的加减号前后不能出现空格,如complex(‘1+2j’)是正确表达,complex(‘1 + 2j’)是错误的。
例子:
1 | complex() #缺省实部和虚部 |
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’) 等价于删除x.foobar
1 | class A: |
class dict(**kwarg)
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.
创建一个新字典。字典对象是字典类,阅读字典和映射类型——字典文档,来了解这一类。
在内置列表,集合,元类和收集模块查看其他其他容器。
1 | help(dict) #help的解释 |
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:
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([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:
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.
如果没有输入参数,返回当前窗口内参数的列表;如果输入参数则尝试返回一个此对象有效属性的列表:
1 | dir() |
如果对象有一个名为__dir__()的方法,则返回此属性的列表:
1 | class B: |
当参数对象是类时,返回类及其子类的属性、方法列表:
1 | class A: |
当参数是模块时,返回一个包含模块属性的列表:
1 | import math |
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)
对于浮点数,结果等同于(math.floor(a/b),a % b)
1 | divmod(5,2) |
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.
返回一个枚举的对象。可迭代的必须是一系列的或一个迭代器或一些其他支持迭代的对象。通过enumerate()返回的__next__()方法返回一个包含计数(默认从0开始)和从可迭代的对象中迭代的值的元组。
1 | 'Spring', 'Summer', 'Fall', 'Winter'] #默认从0开始 seasons = [ |
它相当于
1 | def enumerate(sequence, start=0): |
eval(expression, globals=None, locals=None)
exec(object[, globals[, 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.
从可迭代对象中函数返回为真的的元素中创建一个迭代器,可迭代对象可以是序列,也可以是一个支持迭代的容器,或是一个迭代器,如果函数是None,将移除可迭代对象中所有为false的元素(比如空字符串,空序列,空字典之类)
1 | list(range(1,10)) a= |
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:
返回一个有一个数字或字符串构成的浮点数。
如果输入的参数是一个字符串,那么这个字符串应该包含一个小数,可选择性的在前面加上些符号,也可选择性的植入空白字符。这些可选择的符号可以是,’+’或’-‘; ‘+’对产生的值没有任何影响。输入的参数也可以是一个字符串,来表示非数值(NaN)或正(负)无穷。更准确的说,输入的必须符合下列被移除的前导和后缀空白字符的语法。
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.
这里的floatnnumber是一种Python用浮点数表示的浮点数字符。形式并不重要,举个例子,“inf”, “Inf”, “INFINITY”和“iNfINity”对于正无穷都是可接受的拼写。
另外,如果输入参数是一个整数,或一个浮点数,返回一个与它的值相等的浮点数。如果这个参数超出Python浮点数能表示的范围,则返回OverflowError。
如果没有输入参数,则返回0.0
1 | float() |
format(value[, format_spec])
class frozenset([iterable])
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.
将一个值