Python中文文档-2.内置函数

Python解释器有很多可用的内置函数和类型,如下所示(字母排序)

内置函数表

abs(x)

返回X的绝对值,X可以是int或float类型,如果X是复数则返回它的模大小。

all(iterable)

如果迭代器的元素全是True 或 迭代器为空就返回True。0算是False。
(全是True才行)
等价于如下代码:

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

any(iterable)

如果迭代器的元素任意一个元素是True就返回True。
(有一个就True了)
如果迭代器为空就返回False
等价于如下代码:

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

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()一样,返回一个包含 可打印表示的对象Object 的字符串,但会用把非ASCII字符转义成由repr()使用\x,\u或\U转义返回的字符串。他返回一个类似在python2中repr()返回的字符串。

s=
  'fwfwfq\newfe\n\tfw\n\t'
ascii(s)=
  "'fwfwfq\\newfe\\n\\tfw\\n\\t'"
repr(s)=
  "'fwfwfq\\newfe\\n\\tfw\\n\\t'"

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.

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

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'

If prefix “0b” is desired or not, you can use either of the following ways.
你可以使用以下方法选择是否需要前缀 '0b'

>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')

See also format() for more information.
查看format()函数获取更多信息

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。bool类是int的子类,并且不能再细分下去。它的实例只有False和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.

返回一个bytes类型的新数组。bytearray类是一个可变的integer类型(0<=x<256)的序列.它拥有 由可变序列类型解释的可变序列 大部分的方法,以及bytes类型所拥有的大部分方法。

The optional source parameter can be used to initialize the array in a few different ways:
可选的source参数可用于初始化数组:

  • 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.
  1. 如果是字符串,你必须提供encoding参数;bytesarray()会使用str.encode()把string转为bytes。
  2. 如果是int类型,bytearray会得到它的大小n然后初始化为n个null bytes
  3. 如果是一个符合缓冲接口的对象,一个对象的只读缓冲流会用于初始化bytes array
  4. 如果是迭代器,它必须是(0<=x<256)范围可迭代的integer,这些integer会用作初始化数组的内容。

Without an argument, an array of size 0 is created.
没有参数,就会产生一个大小为0的数组

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

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.

返回一个新的bytes对象,它是(0<=x<256)范围的integer的不可变序列。bytes是bytesarray的一个不可变的版本。它拥有同样的 不改变本身的方法 以及同样的索引和切片行为。

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

因此,构造器的参数被解释成bytearray()

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

Bytes对象也可以用文字创建,具体看String 和 Bytes literals.

>>> b = bytes('dwfawfa',encoding='utf-8')
>>> b
b'dwfawfa'

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

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.

如果object参数是可调用的,就返回True,否则为False。如果它返回True,这仍然有可能call失败;但如果返回false,则调用Object永远都不可能成功。注意,类都是可调用的(调用一个类返回一个新的实例)。如果实例的类含有call()方法,则它们是可调用的。

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

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().

返回string表示Unicode编码是 i 的字符。例如:chr(97)返回string 'a',chr(8364)返回的是string '€'. 它是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.

有效范围是0到1,114,111 (0x10FFFF)。超过范围会导致值错误。

>>> chr(-1)
Traceback (most recent call last):
  File "<pyshell#78>", line 1, in <module>
    chr(-1)
ValueError: chr() arg not in range(0x110000)

@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:

一个类方法隐式的接收类作为第一个参数,就像实例方法接收实例本身一样
[ 参考类中的实例方法def func(self,*args)的self ]。
为了声明类方法,要用如下语法:

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.

@classmethod 格式是一个方法装饰器,在 function definitions in Function definitions 部分可以了解详细信息。

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 BaseA(object):
    @classmethod
    def func_a(cls):
        print(type(cls), cls)

class ClassA(BaseA):
    pass

if __name__ == '__main__':
    ClassA.func_a()
    ca = ClassA()
    ca.func_a()
-----------------------------
结果:
<class 'type'> <class '__main__.ClassA'>
<class 'type'> <class '__main__.ClassA'>

Class methods are different than C++ or Java static methods. If you want those, see staticmethod() in this section.

类方法和C++、JAVA的静态方法不同。可以看本章节的staticmethod()了解更多。

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

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.

compile把source编译成代码对象或者AST(抽象语法树)对象。代码对象可以被exec()或eval()执行。source可以是普通字符串,byte字符串,或者AST对象。参考AST章节了解AST对象如何工作。

  • 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).
    filename参数应该提供有可读代码的文件。如果没有可从文件读取的内容,就传递一些可识别的值。如: ""

  • 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).
    mode参数指定编译什么类型的代码。如果source包含序列语法可以用'exec';如果包含单一的表达式'eval';若包含单一的交互语法可以使用‘single’。(后一种情况将会把非None的表达式语句打印出来)

  • The optional arguments flags and dont_inherit control which future statements affect the compilation of source. If nei。her 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.
    (这段话很难理解)
    可选参数flags(int)和dont_inherit(int)控制哪个将来的语句会影响源的编译。
    如果两者都没有给出或都是0, the code is compiled with those future statements that are in effect in the code that is calling compile()。
    如果给了flags没有给dont_inherit(或为0),除了那些被会被使用的语句以外,被flags指定的未来语句也会被使用。
    如果dont_inherit是一个非零整数,那么flags参数就是它 - 忽略了对编译调用有效的未来语句。

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.

未来语句是由位来指定的,这些位可以被一起或运算来指定多个语句。位字段要求指定一个给定的特征,这个特征可以在_Feature实例中的 __future__模块中找到作为compiler_flag。

  • 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).
    optimize参数指定编译器的优化级别,默认值-1选择解释器的优化级别是-O。明确指定的级别是0:不优化,__debug__==true;1:不维护,__debug__==false;2:文档注释被移除
>>>str = "for i in range(0,5): print(i)" 
>>> c = compile(str,'','exec')   # 编译为字节代码对象 
>>> c
<code object <module> at 0x10141e0b0, file "", line 1>
>>> exec(c)
0
1
2
3
4
>>> str = "3 * 4 + 5"
>>> a = compile(str,'','eval')
>>> eval(a)
17

This function raises SyntaxError if the compiled source is invalid, and ValueError if the source contains null bytes.

如果source有语法错误会导致SyntaxError,若source包含null bytes会导致ValueError

If you want to parse Python code into its AST representation, see ast.parse().
如果想把python代码转换为AST表达,查看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.

注意,当使用'single'或'eval'模式编译一个多行的字符串代码,输入必须要用至少一个换行符来结束。这是为了便于在代码模块中检测不完整和完整的语句。

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.

警告,如果使用足够复杂/庞大的字符串来编译AST对象的时候,会有可能会导致python解释器的崩溃。因为Python的AST编译器的栈深度限制。

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.

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.

返回一个值为real + imag*1j 的复数或转换一个字符串 或 数字为复数。如果第一个参数是一个字符串,那么它将被解释为一个复数,并且必须在没有第二个参数的情况下调用该函数。第二个参数永远不可以是一个字符串。每个参数可以是任意的数字类型(包括复数)。如果imag省略了,它默认是0,构造器把它当作一个int/float的数字转换。如果两个参数都是空,就返回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.

注意当转换字符串的时候,字符串必须在运算符两边不包含空格。例如:

>>> complex('1+2j')
(1+2j)
>>> complex('1 +2j')
Traceback (most recent call last):
  File "<pyshell#110>", line 1, in <module>
    complex('1 +2j')
ValueError: complex() arg is a malformed string

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

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,793评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,567评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,342评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,825评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,814评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,680评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,033评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,687评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,175评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,668评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,775评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,419评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,020评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,978评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,206评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,092评论 2 351
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,510评论 2 343

推荐阅读更多精彩内容