python interactive函数_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.

如果是字符串,你必须提供encoding参数;bytesarray()会使用str.encode()把string转为bytes。

如果是int类型,bytearray会得到它的大小n然后初始化为n个null bytes

如果是一个符合缓冲接口的对象,一个对象的只读缓冲流会用于初始化bytes array

如果是迭代器,它必须是(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 "", line 1, in

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

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 "", line 1, in

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值