overview

Built-in Functions
abs() delattr() hash() memoryview() set()
all() dict() help() min() setattr()
any() dir() hex() next() slice()
ascii() divmod() id() object() sorted()
bin() enumerate() input() oct() staticmethod()
bool() eval() int() open() str()
breakpoint() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()

abs(x)

返回数值x的绝对值,x可以为:整数和浮点数。如果x是复数,则返回复数的 magnitude,即复数与其共轭复数乘积的正平方根。如:

1
2
abs(2 + 2j)  # (2 + 2j) * (2 - 2j) 的平方根
2.8284271247461903

复数与其共轭复数的乘积运算: (a + bj) * (a - bj) == a ** 2 + b ** 2,因此,abs(a + bj) == math.sqrt(a ** 2 + b ** 2)


all(iterable)

iterable中的所有元素为真,或iterable为空时,返回True


any(iterable)

iterable中有任意一个元素为真时,返回True


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.


bin(x)

将整数x转换为以0b开头的二进制字符串。x为整数或int对象(即该对象必须定义__index__()方法,并返回一个整数)。

1
2
3
4
a = bin(3)  # '0b11'
b = bin(-3) # '-0b11'
int(b, base=2)
-3


bool([x])

根据x的判断值,返回布尔值TrueFalse。如果x为空,返回False

boolint的子类,但是,bool不能够被继承,因为bool的实例只有TrueFalse

1
2
3
4
class A(bool):
pass

TypeError: type 'bool' is not an acceptable base type


breakpoint(*args, **kws)

New in version 3.7


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


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

  • Python 2
    str(object=’’) -> string.
    Return a nice string representation of the object. If the argument is a string, the return value is the same object.

  • Python 3

    • bytes(): empty bytes object.
    • bytes(int): bytes object of size given by the parameter initializated with null bytes (‘\x00’).

      1
      2
      bytes(0)  # b''
      bytes(3) # b'\x00\x00\x00'
    • bytes(iterable_of_ints): bytes

      1
      bytes(range(3))  # b'\x00\x01\x02'
    • bytes(bytes_or_buffer): immutable copy of bytes_of_buffer.

      1
      2
      3
      a = b'abc'
      b = bytes(a) # b'abc'
      a == b # True, i.e. id(a) == id(b)
    • bytes(string, encoding[, errors]): bytes.

      1
      2
      a = 'abc'  # Unicode
      bytes(a, 'utf-8') # b'abc'

callable(object)

判断 object 是否是可调用的,返回Ture/False

  • callable函数只是检测object是否可调用,不管object调用是否成功。object为可调用对象时,调用的时候也可能调用失败;object为不可调用对象时,调用就一定失败。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    class A(object):
    pass

    class B(object):
    def __call__(self):
    return a # global name 'a' is not defined

    callable(A) # True
    callable(A()) # False
    callable(B) # True
    callable(B()) # True
  • 类对象都是可调用的,返回一个类实例。但是类的实例对象是否为可调用对象,取决于类是否定义了__call__()方法。

    1
    2
    3
    4
    callable(int)     # True
    callable(int()) # False
    callable(bool) # True
    callable(bool()) # False

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


chr(i)

Python 2: Return a string of one character with oridinal i (0 <= i < 256).
Python 3: Return a Unicode string of one character with ordinal i (0 <= i <= 0x10ffff).
返回 code point i 对应的 Unicode 的字符,0 <= i <= 0x10ffff。与 ord() 函数作用相反。

1
2
chr(65)   # A
ord('A') # 65


@classmethod


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

source编译成 code 对象或 AST 对象。编译成的 Code 对象可以被execeval函数执行。

  • source: 可以是字符串、byte 字符串或 AST 对象。注意,source的内容要符合mode
  • filename: 字符串类型,读取代码的文件名。如果不是从文件中读取,可以用一些具有标识性的字符串代替,如'<string>'
  • mode: 指定代码编译的类型。

    • 'exec': 如果source是由一系列的 Python 语句组成的。
    • 'eval': 如果source是一条表达式,编译成的代码对象可以被eval函数执行。
    • 'single': 如果source由单一的交互式语句组成。(这种情况下,用exec也是可以的,不知道single的实际作用?!)

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      code_object = compile('a = 1; b = a + 1', '<string>', 'exec')
      exec(code_object)
      a, b
      (1, 2)
      code_object = compile('1 + 1', '<string>', 'eval')
      eval(code_object)
      2
      code_object = compile('name = input("Input your name: ")', '<string>', 'single')
      exec(code_object)
      Input your name: lizs
      print(name)

complex([real[, imag]])

返回实部real和虚部imag转换成的复数。

  • realimag可以是任意的数值类型,如 int, float,complex 等。real还可以是 sting 类型,但imag永远不能够为 string 类型。realimag的默认值都为 0。返回real + imag * 1j

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    complex(1, 2.1)
    (1+2.1j) # 1 + 2.1 * 1j = (1+2.1j)
    complex(1+2j, 2)
    (1+4j) # (1+2j) + 2 * 1j = (1+4j)
    complex(1+2j, 2j)
    (-1+2j) # (1+2j) + 2j * 1j = (1+2j) - 2 = (-1+2j)
    complex(-1.1)
    (-1.1+0j) # -1.1 + 0 * 1j = (1.1+0j)
    complex()
    0j # 0 + 0 * 1j = 0j
  • real为 string 时,real将转换为复数,imag不能有值。

    1
    2
    3
    4
    5
    6
    complex('1')
    (1+0j)
    complex('1.1+1.2j')
    (1.1+1.2j)
    complex('1', '2')
    TypeError: complex() can't take second arg if first is a string
  • 注意,当real为 string 时,real字符串中的+-操作符前后不能够有空格。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    complex('1 + 2j')
    ValueError: complex() arg is a malformed string
    complex('1 - 2j')
    ValueError: complex() arg is a malformed string
    complex('1 ')
    (1+0j)
    complex(' -2')
    (-2+0j)
    complex(' -2j')
    -2j

delattr(object, name)

删除对象object中的属性nameobject为对象名称;name为对象的属性名称,字符串类型。实际上,delattr(x, 'foobar')相当于del x.foobar


dict(kws)/dict(mapping, kws)/dict(iterable, **kws)

字典的构建函数。

  • dict(): new empty dictionary

  • dict(mapping): new dictionary initialized from a mapping object’s (key, value) pairs

  • dict(iterable): new dictionary initialized as if via:

    1
    2
    3
    d = {}
    for k, v in iterable:
    d[k] = v
  • dict(**kwargs): new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2).


dir([object])

返回object的有效的属性名称的列表。如果object为空,则返回当前的局部作用域(局部变量)的名称。

  • dir([object])只是返回属性或变量的名称,locals()globals()分别返回局部和全局符号表(一种映射关系,存储了键值对的数据结构)。

  • 如果object定义了__dir__()方法,则dir(object)会调用object.__dir__()方法,__dir__()方法必须返回一个列表。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    class A(object):
    def __dir__(self):
    print('hello world')
    return ['a', 'b', 0]

    def name(self):
    return 'lizs'

    dir(A())
    hello world
    ['a', 'b', 0] # in this case, just call __dir__() function, and doesn't has 'name' attribute.
  • 如果object没有定义__dir__()方法,dir(object)会从object.__dict__属性,and from its type object.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    class B(object):
    def __init__(self):
    self.__dict__ = {'a': 1, 'b': 2}

    def c(self):
    pass

    dir(B())
    ['__class__', '__delattr__', '__dict__', '__doc__', ..., 'a', 'b', 'c']
    B().a
    1
  • dir([object])的默认机制是:

    • 如果object是 Python 模块,则返回该模块的属性名称组成的列表。
    • 如果object是 type 或 class 对象,则返回object的属性名称,和object基类的属性名称。
    • 否则,则返回object的属性名称,object父类的属性名称,和object父类的基类的属性名称组成的列表。

divmod(a, b)

divmod(a, b) -> (a // b, a % b)


enumerate(iterable, start=0)

返回一个枚举对象,iterable必须是一个序列,或一个迭代器,或其它的迭代对象。

1
2
3
4
5
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')]

相当于:

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


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

globalslocals变量的环境下,返回表达式(Python expression)source执行的值。

  • source,可以是字符串 (Python expression),也可以是一个 code objects (如 compile() 创建的 code object)。
  • globals,字典类型,当globals=None时,默认值为当前环境下的globals()
  • locals,任意映射类型,当locals=None时,默认值为当前环境下的locals()
  • globalslocals参数只能够通过位置参数传参。

    1
    2
    eval('int()', globals={'a': 1})
    TypeError: eval() takes no keyword arguments
  • 如果globals字典参数中没有__builtins__键,则自动添加__builtins__,其值为builtins模块。

    1
    2
    eval('list(globals().keys()), list(locals().keys())', {}, {})
    ['__builtins__', {}]
  • 如果只有globals参数,则locals参数的值默认为globals参数的值。

    1
    2
    eval('list(locals().keys())', {'a': 1})
    ['a', '__builtins__']
  • source为 code object 时,如果 code object 使用compile()创建时使用了exec作为参数mode的值,则返回None

    1
    2
    3
    4
    print(eval(compile('1 + 2', '<string>', 'eval')))
    3
    print(eval(compile('1 + 2', '<string>', 'None')))
    None
  • 注意,print("hello world")只是在屏幕输出内容,表达式没有返回值的。

    1
    2
    3
    4
    5
    6
    7
    8
    a = print('hello world')
    hello world # 屏幕输出
    print(a)
    None # print 函数的返回值为 None
    a = eval("print('hello world')")
    hello world # 屏幕输出
    print(a)
    None # eval 函数执行完的返回值为 None
  • 因为source为 Python 表达式 (expression),所以,当source为 Python 語句 (statement) 时會出錯。如:赋值语句 (=)。

    1
    2
    3
    4
    5
    eval('a = 1')
    File "<string>", line 1
    a = 1
    ^
    SyntaxError: invalid syntax

    要执行 Python statements 可以使用 exec() 函数。


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

eval相似,eval执行 Python 表达式或 code object 并会返回执行结果。exec函数会动态执行source,但返回None

  • source可以是 string 或 code object。source可以是动态的 Python 语句,如a = 1; a += 1
  • globalslocals: 用法和eval相同。

  • Python 2 exec不是函数,而是一个内置语句,不会返回值。

    1
    2
    3
    4
    5
    6
    # Python 2+
    a = exec('a = 1; a + 1')
    File "<ipython-input-21-1d9129f9ba14>", line 1
    b = exec('a = 1; a + 1')
    ^
    SyntaxError: invalid syntax
  • Python 3 exec是内置函数,只返回None

    1
    2
    3
    4
    # Python 3+
    a = exec('1 + 1')
    print(a)
    None

filter(function, iterable)

(Python 2) filter(function or None, sequence) -> list, tuple, or string
Return those items of sequence for which function(item) is true. If function is None, return the items that are true. If sequence is a tuple or string, return the same type, else return a list.

(Python 3) filter(function or None, iterable) –> filter object
Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true.

  • filter函数过滤掉iterable中 item 经过function(item)调用返回不为真的 item。
  • functionNone时,返回iterable中为真的项。
  • Python2,如果iterable为 tuple 或 string 则返回原来的类型,其余类型返回 list;Python3 返回一个 filter object。

    Python 2+:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    filter(int, [0, 1, 2])
    [1, 2]
    filter(int, (0, 1, 2))
    (1, 2)
    filter(int, {0, 1, 2})
    [1, 2]
    filter(int, '012')
    '12'
    def f(x):
    print(x)
    return 65 <= ord(x) <= 90
    filter(f, 'abAB')
    a
    b
    A
    B
    'AB' # filter the 'ab'
    filter(None, [0, 1, 2])
    [1, 2]
    filter(None, (0, 1, 2))
    (1, 2)
    filter(None, '012')
    '012'

    iterable为字符串类型并且第一个参数不为None时,会遍历字符串中的每个字符作为 item 传给 function

    Python 3+:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    r1 = filter(int, [0, 1, 2])
    print(r1)
    <filter object at 0x...>
    list(r1)
    [1, 2]

    def func(x):
    print(x)
    return 65 <= ord(x) <= 90

    r2 = filter(func, 'abAB')
    next(r2)
    a
    b
    A
    'A' # yielding 'A', beause function('A') == True.
    next(r2)
    'B'
    list(filter(None, (0, 1, 2)))
    [1, 2]
    list(filter(None, '012'))
    ['0', '1', '2']
    list(filter(int, '012'))
    ['1', '2']
    list(filter(bool, '012'))
    ['0', '1', '2']

float([x])

x转换为浮点数。x可以是 string 或 int。

  • 如果x是 string 类型,x应该是一个十进制数字的字符串,或(inf/Infinity)代表无穷大值,字符串前面可以包含+-或空格字符。如果没有参数,则返回0.0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    float(1)
    1.0
    float(1.11)
    1.11
    float('1')
    1.0
    float('+1.11')
    1.11
    float(' -123\n')
    -123.0
    float('1e-003')
    0.001
    float(' +1E6')
    1000000.0
    float('inf')
    inf # 正无穷大
    float('-Infinity')
    -inf # 负无穷大

format(value[, format_spec])

返回value.__format__(format_spec)format_spec默认值为空字符串。
See the Format Specification Mini-Language section of help(‘FORMATTING’) for
details.


forzenset([iterable])

创建一个 frozenset 对象。iterable为可迭代对象,如果iterable为空,则创建一个空值的 frozenset 对象。

1
2
3
4
5
6
7
8
frozenset()
frozenset() # an empty frozenset object
frozenset('abcde')
frozenset({'a', 'b', 'c', 'd', 'e'})
frozenset([0, 1, 2, 'abc'])
frozenset({0, 1, 2, 'abc'})
frozenset(0)
TypeError: 'int' object is not iterable


getattr(object, name[, default])

获取object对象的属性名称为name的值,name必须为字符串类型。即getattr(object, name)相当于object.name。当object.name不存在时,如果指定default的值,则返回default的值;如果不指定default的值,则会引起AttributeError错误。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class A(object):
def __init__(self):
self.name = 'lizs'
self.age = 18

def address(self):
return 'China'

getattr(A(), 'name')
'lizs'
getattr(A(), 'address')
<bound method A.address of <__main__.A object at 0x...>>
getattr(A, 'name')
AttributeError: type object 'A' has no attribute 'name'
getattr(A, 'name', 'lizs')
'lizs'


globals()

返回全局符号表。


hasattr(object, name)

判断object对象是否存在属性name,返回TrueFalsename,字符串类型,属性的名称。e.g. hasattr(People, 'age')相当于People.age

实际上,hasattr(object, name)调用了getattr(object, name),然后通过抓取错误来判断是否存在属性。


hash(object)

获取object对象的哈希值。哈希值为整数,两个数值比较为相等时,它们的哈希值相同。

1
2
3
4
5
6
hash(1), hash(1.0), hash(1+0j)
(1, 1, 1)
1 == 1.0 == 1+0j
True
id(1), id(1.0), id(1+0j)
(94326139635240, 94326148389728, 139691410895376)


help([object])

打印object的帮助文档信息,当没有参数时,启动一个帮助系统的交互界面。


hex(x)

将整数x转换为十六进制字符串(以0x开头的小写字母字符串)。

1
2
3
4
hex(255)
'0xff'
hex(-42)
'-0x2a'


id(object)

获取对象的 identity。在对象的生命周期中,identity 是一个具有唯一性的常数。
在 CPython 解析器中,identity 就是该对象的内存地址。


input([prompt])

从基础输入中读取一行信息,即input()读取到换行符结束。或用户自动出发结束,如Linux系统Ctrl + D。如果提示信息prompt给出,则在基础输出中显示。prompt显示的时候不会自动加换行。

1
2
3
4
5
6
7
input("Hi, what is your name: ")
Hi, what is your name: lizs # 提示信息不会自动换行,输入信息 'lizs' 会随尾提示后面。
'lizs'
input("Hi, what is your name: \n")
Hi, what is your name:
lizs # input message
'lizs'


int([x])/int(x, base=10)

  • 当没有参数时,返回 0,即int() == 0
  • 如果x定义了__int__(),则返回x.__int__();如果x定义了__trunc__(),则返回x.__trunc__()
  • x为浮点数时,返回整数部分。

    1
    2
    int(1.9)
    1
  • x不是数字的时候,或当指定base的值的时候,x只能是 string, bytes, bytearray 代表的整形字面量(integer literal)。这时x可以以+-开头,或空格围绕。

    1
    2
    int(' - 101 ')  # base=10
    -101

    Python 3+ integer literal definitions:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    integer      ::=  decinteger | bininteger | octinteger | hexinteger
    decinteger ::= nonzerodigit (["_"] digit)* | "0"+ (["_"] "0")*
    bininteger ::= "0" ("b" | "B") (["_"] bindigit)+
    octinteger ::= "0" ("o" | "O") (["_"] octdigit)+
    hexinteger ::= "0" ("x" | "X") (["_"] hexdigit)+
    nonzerodigit ::= "1"..."9"
    digit ::= "0"..."9"
    bindigit ::= "0" | "1"
    octdigit ::= "0"..."7"
    hexdigit ::= digit | "a"..."f" | "A"..."F"

    Python 2 integer literal definitions:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    longinteger    ::=  integer ("l" | "L")
    integer ::= decimalinteger | octinteger | hexinteger | bininteger
    decimalinteger ::= nonzerodigit digit* | "0"
    octinteger ::= "0" ("o" | "O") octdigit+ | "0" octdigit+
    hexinteger ::= "0" ("x" | "X") hexdigit+
    bininteger ::= "0" ("b" | "B") bindigit+
    nonzerodigit ::= "1"..."9"
    octdigit ::= "0"..."7"
    bindigit ::= "0" | "1"
    hexdigit ::= digit | "a"..."f" | "A"..."F"
  • base表示x的进制数,如int('101', 8)表示101是一个八进制的字符串,转换为整数则为:1 * 8 ** 0 + 0 + 1 * 8 ** 2 == 65base的有效值可以为 0 和 2-36。

    • base=0时,意味着x按照 integer literal 转换。但 Python 2+ 与 Python 3+ 的integer literal 有些不同,如当x是以 0 开头时在 Python 3+ 是不合法的,但在 Python 2+ 中为 octinteger int('010', 0) == int('010', 8)
    • base为 2, 8, 16 时,x可以分别以0b/0B, 0o/0O0x/0X开头。
    • base的值大于 10 时,x可以用字母 a-z 或 A-Z 来表示 10 - 35 (注意,字母必须小于base,如当base=12时,x中只能够有字母ab)。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    int('101', 8)
    65
    int('101', 0) # decinteger
    101
    int('0b101', 0) # bininteger
    5
    int('0Xa0', 0) # hexinteger
    160
    int('a0', 0)
    ValueError: invalid literal for int() with base 0: 'a0'
    int('101', 2)
    5
    int('0B101', 2)
    5
    int('ab1', 12)
    1573

isinstance(object, classinfo)

判断object是否是classinfo的实例,返回True/Falseclassinfo可以是一个类或一个由若干个类型组成的元组。当classinfo是元组时,只要object属于classinfo中任意一个类型的实例则返回True

1
2
3
4
5
6
isinstance(0, object)
True
isinstance(0, (str, int, dict))
True
isinstance(0, ('a', int))
TypeError: isinstance() arg 2 must be a type or tuple of types


issubclass(class, classinfo)

判断class是否是classinfo的子类,返回True/Falseclassinfo可以是一个类或一个由若干个类组成的元组。当classinfo是元组的时候,只要class属于classinfo中任意一个类的子类则返回True

1
2
3
4
issubclass(int, object)
True
issubclass(int, (str, object, dict))
True

isinstance(object, classinfo)不同,issubclass(class, classinfo)的第一个参数class必须是一个类,并且class认为是其本身的子类。

1
2
3
4
5
6
issubclass(0, object)
TypeError: issubclass() arg 1 must be a class
issubclass(int, int)
True
isinstance(int, int)
False


iter(object[, sentinel])

iter(collection) -> iterator
iter(callable, sentinel) -> iterator

  • 当没有sentinel参数时,第一个参数只能够是 collection 对象,即支持迭代协议(__iter__()方法)和序列协议(__getitem__()方法)。

    1
    2
    3
    i = iter([0, 1, 2])
    next(i) # 0
    next(i) # 1
  • 当第二个参数不为空的时候,第一个参数必须是一个可调用对象。创建的迭代器在每次迭代的时候,会调用callable,当调用的返回值为sentinel时停止。

    1
    2
    3
    with open('mydata.txt') as fp:
    for line in iter(fp.readline, ''):
    print(line)

len(s)

获取对象s的长度(元素个数)。

1
2
3
4
5
6
7
8
len('abc')
3
len({'a', 'b', 'c'})
3
len(dict(a=0, b=1, c=2))
3
len(range(10))
10


list([iterable])

list() -> new empty list
list(iterable) -> new list initialized from iterable’s items


locals()

获取当前局部符号表,即当前范围的局部变量组成的字典。


map(function, iterable[, iterable, ..])

(Python2.7) Apply function to every item of iterable and return a list of 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. If one iterable is shorter than another it is assumed to be extended with None items. If function is None, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list.
(Python3+) 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 iterable stops when the shortest iterable is exhausted.

  • function应用于iterable的每一项,返回列表(Python3+,迭代对象),列表(迭代对象)中的每一项都是function作用后的结果。注意:Python3+ 返回的是迭代对象。

  • 如果有多个iterablefunction将并行应用于iterable的每一项。也即是,所有iterable中相同序列的项同时作为参数传递给function运行。如:

    1
    2
    3
    4
    5
    6
    7
    8
    map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6])
    [5, 7, 9] # Python3+ 返回迭代器<map object>
    map(lambda x: x * x, [1, 2, 3], [4, 5, 6])
    TypeError: <lambda>() takes exactly 1 argument (2 given)
    def func(*args):
    return args
    map(func, [1, 2, 3], [4, 5, 6], [7, 8, 9])
    [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
  • iterable的个数(注意,不是iterable元素个数)与function函数的参数不一致时会出错。如:

    1
    2
    map(lambda x: x * x, [1, 2, 3], [4, 5, 6])
    TypeError: <lambda>() takes exactly 1 argument (2 given)
  • 当有多个iterable并且iterable的元素数目不一致时:Python2,会以最长的为准,短自动用None补全。Python3+,以最短的为准,迭代完最短的iterable就会自动结束。

    1
    2
    3
    4
    5
    6
    7
    8
    def func(*args):
    return args
    # Python2.7
    map(func, [1, 2, 3], [4, 5, 6, 7])
    [(1, 4), (2, 5), (3, 6), (None, 7)]
    # Python3+
    list(map(func, [1, 2, 3], [4, 5, 6, 7]))
    [(1, 4), (2, 5), (3, 6)]
  • functionNone

    1
    2
    3
    4
    5
    6
    # Python2
    map(None, [1, 2, 3], [4, 5, 6, 7])
    [(1, 4), (2, 5), (3, 6), (None, 7)]
    # Python3+
    list(map(None, [1, 2, 3], [4, 5, 6, 7]))
    TypeError: 'NoneType' object is not callable

max()

max(iterable, *[, key=func, default=obj])
max(arg1, arg2, *args[, key=func])

  • 当只有一个位置参数的时候(即第一种模式),这个参数只能是一个可迭代对象,函数会返回迭代对象中最大的一个元素。如:list, str, tuple 等。

    1
    2
    3
    4
    max('0123')
    3
    max([0, 1, 2, 3])
    3
  • 如果有两个或两个以上位置参数(即第二种模式),则返回这些参数中最大的一个。注意,这些位置参数一定要可比较大小的,不然会出错。Python3 两个不同类型之间不可以比较大小。

    1
    2
    3
    4
    5
    6
    7
    8
    max(0, 1, 2)
    2
    # Python 2+
    max('a', 1, 2)
    'a' # 'a' > 2 == True, in python 2
    # Python 3+
    max('a', 1, 2)
    TypeError: '>' not supported between instances of 'str' and 'int'
  • 除了位置参数之外,max()还有 keyword-only 参数key=funckey参数和list.sort()key参数类似。key参数的值为接收一个参数的函数(如func(x)),iterable中的元素或各个位置参数会作为参数传给func函数处理,max()函数会根据func函数的返回值进行比较取最大值。

    1
    2
    3
    4
    5
    # Python 3
    max(['a', 0, 1, 97], key=lambda x: ord(x) if isinstance(x, str) else x)
    'a'
    max('a', 0, 98, key=lambda x: ord(x) if isinstance(x, str) else x)
    98

    原本 Python 3+ 是不能够比较 str 和 int 的,但是key参数自动将字符串转换为了整数。同时,当比较的参数中有相同的时候,会返回第一个最大值(ord('a') == 97)。

  • Python 3.4 以上,第一种模式max(iterable, *[, key=func, default=obj])新增了一个 keyword-only 参数 default=objdefault参数可以指定当iterable为空的时候,函数返回的默认值。

    1
    2
    max('', default=1)
    1

min()

min(iterable, *[, key=func, default=obj])
min(arg1, arg2, *args[, key=func])

用法和max()函数一样,功能相反,返回参数中的最小值。


memoryview(object)

创建 memoryview 对象。

1
2
3
4
5
6
7
8
9
10
11
12
a = bytearray(1000000)
sys.getsizeof(a)
1000057
b = memoryview(a)
print(b)
<memory at 0x...>
print(sys.getsizeof(b))
192
print(b[1])
0
print(b[1:3])
<memory at 0x...>


next(iterator[, default])

返回迭代器iterator的下一个元素,即调用iterator.__next__()的返回值。next()的第二个参数为iterator遍历结束时返回的默认值,否则当iterator迭代完的时候会引起StopIteration错误。

1
2
3
4
5
6
7
8
9
10
a = iter(range(2))
next(a) # 0
next(a) # 1
next(a) # StopIteration
a = iter(range(3))
next(a) # 0
next(a, 3) # 1
next(a, default=3) # TypeError: next() takes no keyword arguments
next(a, 3) # 2
next(a, 3) # 3

当给出第二个参数的时候,当迭代器迭代完毕的时候会返回这个默认值,而不会引起StopIteration错误。同时,next()的第二个参数是一个位置参数。


oct(x)

将整数x转换为以0o开头的八进制(octal)字符串。x为整数或int对象(即该对象必须定义__index__()方法,并返回一个整数)。注意,Python 2+ 八进制字符串以0开头。

1
2
3
4
oct(3)   # 0o3
oct(10) # 0o12
int('0o12', 8)
10


open()

open(name[, mode[, buffering]])
open(file, mode=’r’, buffering=-1, encoding=None, errors=None, newlin
e=None, closefd=True, opener=None)


ord(c)

获取 Unicode 单个字符c的 code point。与chr(x)功能相反。

1
2
3
4
ord('a')
97
chr(97)
'a'


pow(x, y[, z])

当只有两个参数时,返回 x ** y;当由三个参数时,返回x ** y % z


print()

Python 2+: print()函数实际上是print表达式。
Python 3+: print(value, …, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)

  • Python 2+,print()函数实际上是print表达式,所以,是没有关键字参数的,并且,多个位置参数时,是当做元组处理。

    1
    2
    3
    4
    print('a', 'b')
    ('a', 'b')
    print('a', 'b', sep='|')
    SyntaxError: invalid syntax
  • Python 3+,print()函数不是关键字参数都会转换成字符串,并且组成一个由sep连接和end结尾的字符串输出。

    • sep=' ',关键字参数,表示当有多个位置参数时的连接符,默认值为空格。
    • end='\n',关键字参数,表示添加到字符串结尾的字符。
    • file=sys.stdout, 关键字参数,必须是有wirite(string)方法的对象。
    • flush=False,关键字参数,表示是否刷新缓冲区。
    1
    2
    3
    4
    5
    print('a', 'b')  # a b
    print('a', 'b', sep='|') # a|b
    print('a', 'b', sep='|', end='===') # a|b===
    with open('test.py', 'w') as fp:
    print('#!/usr/bin/env', 'python', file=fp)

property(fget=None, fset=None, fdel=None, doc=None)

创建一个 property 属性。fget是用来获取该属性值的相关函数,fset用来设置该属性值的函数,fdel是用来删除该属性的函数,doc是一个文档信息字符串。

1
2
3
4
5
class C(object):
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.")

这样便通过property()创建了C对象的属性x

以上操作也可以同 @property 装饰器更简单地实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class C(object):
def __init__(self):
self._x = None

@property
def x(self):
"""I am the 'x' property."""
return self._x

@x.setter
def x(self, value):
self._x = value

@x.deleter
def x(self):
del self._x


range()

range(stop)
range(start, stop[, step])

  • Python 2+, range()返回一个列表对象;Python 3+,range()返回的是一个 range 对象。
  • range()遵循左闭右开原则: [start, stop)
  • 当只有一个参数的时候代表的是 stop,start 默认为 0,即 [0, stop)。
  • 当有两个参数的时候,分别为 start 和 stop,即 [start, stop)。
  • 第三个参数 step 代表步长,默认值为 1,。当 step 为负数的时候,start + step < stop 才有意义。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    # python 2+
    range(10)
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # 左闭右开 [0, 10)
    range(10, 0)
    []
    range(0, 10, 2)
    [0, 2, 4, 6, 8]
    range(0, 10, -2)
    []
    range(10, 0, -2)
    [10, 8, 6, 4, 2]
    range(0, -10, -2)
    [0, -2, -4, -6, -8]
    # python 3+
    range(10)
    range(0, 10)

当 step 为负数的时候,range(10, 0, -2)

1
2
3
4
5
6
10 
8 # 10 - 2
6 # 8 - 2
4 # 6 - 2
2 # 4 - 2
0 # 2 - 2,左闭右开原则,舍弃

所以,list(range(10, 0, -2)) == [10, 8, 6, 4, 2]


repr(object)

Return the canonical string representation of the object.

For many object types, including most builtins, eval(repr(obj)) == obj.

A class can control what this function returns for its instances by defininga __repr__() method.


reversed(seq)

返回seq反转之后的生成器。

1
2
3
4
5
6
7
8
9
a = reversed('abcde')
print(a)
<reversed at 0x...>
next(a)
'e'
next(a)
'd'
list(a)
['c', 'b', 'a']


round(number[, ndigits])

返回number四舍五入之后的结果,第二个参数ndigits表示精度。当没有第二个参数或为None时,返回number四舍五入之后的整数。

1
2
3
4
5
6
7
8
9
10
11
12
round(0.5)
0
round(1.5)
2
round(1.545, 0)
2.0
round(1.545, 1)
1.5
round(1.545, 2)
1.54 # In python 1.545 actually is 1.54499999...
round(1.545000001, 2)
1.55


set([iterable])

set() -> new empty set object
set(iterable) -> new set object

Build an unordered collection of unique elements.


setattr(object, name, value)

Sets the named attribute on the given object to the specified value.
setattr(x, 'y', v) is equivalent to x.y = v


slice()

slice(stop)
slice(start, stop[, step])

Create a slice object. This is used for extended slicing (e.g. a[0:10:2])

1
2
3
4
5
6
7
8
9
10
11
12
a = 'abcdef'
s = slice(2)
print(s)
slice(None, 2, None)
s1 = slice(1, 5)
print(s1)
slice(1, 5, None)
s2 = slice(10, 1, -2)
print(10, 1, -2)
a[s] # 'ab'
a[s1] # 'bcde'
a[s2] # 'fd'


sorted(iterable, *, key=None, reverse=False)

返回iterable排序之后的列表。

  • 关键字参数key,与max()min()list.sort()中的key参数一样,为只有一个参数的函数。如果指定了key=funciterable中的每个元素 item 会作为唯一参数传递给func(item)sorted()函数将根据func(item)的返回值进行比较,值越小越靠前。
  • 关键字参数reverse,布尔值TrueFalse,默认值为False。如果为True则将排序好的列表值反转。

    1
    2
    3
    4
    sorted(('a', 0, 1, 96, 97, 98), key=lambda x: ord(x) if isinstance(x, str) else x)
    [0, 1, 96, 'a', 97, 98]
    sorted('abcde', reverse=True)
    ['e', 'd', 'c', 'b', 'a']

@staticmethod

Convert a function to be a static method.


str

str(object=’’) -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to ‘strict’.


sum(iterable[, start])

返回iterable中各个元素的总和。如果,给出第二个参数start,则返回iterable + start的总和。

1
2
3
4
sum(range(10))
45
sum(range(10), 10)
55


super()

super() -> same as super(class, )
super(type) -> unbound super object
super(type, obj) -> bound super object; requires isinstance(obj, type)
super(type, type2) -> bound super object; requires issubclass(type2, type)
Typical use to call a cooperative superclass method:

1
2
3
4
5
6
7
8
class C(B):
def meth(self, arg):
super().meth(arg)
This works for class methods too:
class C(B):
@classmethod
def cmeth(cls, arg):
super().cmeth(arg)

Python 的super()函数可以用来调用父类的方法,并且有效解决了多重继承中父类方法被多次调用的问题。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class A(object):
def __init__(self):
print('A.__init__')

class B(A):
def __init__(self):
A.__init__(self)
print('B.__init__')

class C(A):
def __init__(self):
A.__init__(self)
print('C.__init__')

class D(B, C):
def __init__(self):
B.__init__(self)
C.__init__(self)
print('D.__init__')

D()
A.__init__
B.__init__
A.__init__
C.__init__
D.__init__
<__main__.D at 0x7f7c5c410710>

可以看到A被初始化了两次,这不是我们想要的。super()很完美的解决了这个问题。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class A(object):
def __init__(self):
print('A.__init__')

class B(A):
def __init__(self):
super().__init__() # super(B, self).__init__()
print('B.__init__')

class C(A):
def __init__(self):
super().__init__() # super(C, self).__init__()
print('C.__init__')

class D(B, C):
def __init__(self):
super().__init__() # super(D, self).__init__()
print('D.__init__')

D()
A.__init__
C.__init__
B.__init__
D.__init__
<__main__.DD at 0x7f6281c98c18>

这次并没有重复的了,A, B, C, D都是只初始化了一次。super()会根据 MRO (method resolution search order) 来查找。

1
2
D.mro()
[__main__.D, __main__.B, __main__.C, __main__.A, object]

  • 开始执行D.__init__()的时候,遇到了super()/super(D, self),则以当前类D (第一个遇到super的类) 的 MRO 来查找。如super(D, self)则查找 MRO 中 D 右侧的下一个对象 B,将 B 的__init__()绑定到当前的self(D()) 执行。
  • 当执行B.__init__()的时候,又遇到了一个super()/super(B, self),这时候还是以之前的 D.mro() 来查找,找到了 B 的下一个 C,继续执行。
  • 当执行C.__init__()的时候,又遇到了一个super()/super(C, self),还是以第一次的 D.mro() 来查找,找到了 C 的下一个 A,继续执行。
  • 当执行A.__init__()的时候,没有super()。OK,执行完,依次返回:A.__init__(), C.__init__(), B.__init__(), D.__init__()

再来看一个对比的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class A(object):
def __init__(self):
print('A.__init__')

class B(object):
def __init__(self):
print('B.__init__')

class C(A):
def __init__(self):
super().__init__() # super(C, self).__init__()
print('C.__init__')

class D(A):
def __init__(self):
super().__init__() # super(D, self).__init__()
print('D.__init__')

class E(C, B, D):
def __init__(self):
super().__init__() # super(E, self).__init__()
print('E.__init__')

E.mro()
[__main__.E, __main__.C, __main__.B, __main__.D, __main__.A, object]
E()
B.__init__
C.__init__
E.__init__
<__main__.E at 0x7f6281c9d3c8>

  • 首先执行E.__init__(),遇到super()/super(E, self),则按照 E.mro() 来查找。找到了 E 的下一个 C。
  • 执行C.__init__()的时候,遇到super()/super(C, self),还是按照 E.mro() 来查找。找到了 C 的下一个 B。
  • 执行B.__init__()的时候,没有super(),执行完依次返回: B.__init__, C.__init__, E.__init__

从以上例子,可以很清楚super(type, obj)就是调用厨师 MRO 中type的下一个对象,并绑定到obj去执行。所以,我们可以指定特别的父类type。同时注意,isinstance(obj, type) == True

上面的例子改一下 E:

1
2
3
4
5
6
7
8
9
10
11
12
class E(C, B, D):
def __init__(self):
super(B, self).__init__()
print('E.__init__')

E.mro()
[__main__.E, __main__.C, __main__.B, __main__.D, __main__.A, object]
E()
A.__init__
D.__init__
E.__init__
<__main__.E at 0x7f6281c9dbe0>

  • 首先执行E.__init__(),遇到super(B, self),则以 E.mro() 来查找,找到 B 的下一个 D。
  • 执行D.__init__()的时候,遇到super()/super(D, self),继续以 E.mro() 来查找 D 的下一个 A。
  • 执行A.__init__(),没有super(),执行完,一次返回:A.__init__, D.__init__, E.__init__

super(type, type2)的第二个参数为 type 时,issubclass(type2, type)必须为True。用法和super(type, obj)类似。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class A(object):
@classmethod
def cmeth(cls):
print('A.cmeth')

class B(A):
@classmethod
def cmeth(cls):
super().cmeth() # super(B, cls).cmeth()
print('B.cmeth')

B.mro()
[__main__.B, __main__.A, object]
B.cmeth()
A.cmeth
B.cmeth

Python 3+, super() -> same as super(class, )


tuple()

tuple() -> empty tuple
tuple(iterable) -> tuple initialized from iterable’s items

If the argument is a tuple, the return value is the same object.


type()

type(object) -> the object’s type
type(name, bases, dict) -> a new type

  • type(object): 返回object的类型。
  • type(name, bases, dict): 创建一个新的对象。实际上,相当于用class创建类的动态格式,A = type('AName', (object,), dict(a=0, b=1))
    • name,新建对象的名称,相当于__name__
    • bases,元组类型,定义新对象继承的基类,即__bases__属性。
    • dict,字典类型,定义新对象的属性。
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
         class A(object):
      def __init__(self):
      self.name = 'lizs'
      self.age = 18
      def a_func(self):
      pass

      class B(object):
      def __init__(self):
      self.height = 165
      self.weight = 138
      def b_func(self):
      pass

      C = type('CName', (A, B), dict(address='China'))
      C
      __main__.CName
      C.__name__
      'CName'
      C.__bases__
      (__main__.A, __main__.B)
      C.mro()
      [__main__.CName, __main__.A, __main__.B, object]
      dir(C)
      ['__class__', ..., 'address', 'a_func', 'b_func']
      dir(C())
      ['__class__', ..., 'address', 'age', 'name', 'a_func', 'b_func']

vars([object])

vars([object]) -> dictionary

Without arguments, equivalent to locals().
With an argument, equivalent to object.dict.


zip(*iterables)

Python2: zip(seq1[, seq2, seq3, …]) -> [(seq1[0], seq2[0], seq3[0], …), (seq1[1], seq2[1], seq3[1], …), …]
Python3: zip(iter1[, iterf2, iter3, …]) -> zip object

zip 函数将各个参数中相同序列的项组成元组,并返回元组组成的迭代器对象(Python 2返回列表)。当各个参数中元素个数不一致时(len(x)),以最短的参数为标准。

Python 3 中 zip 函数的实现实际上等于:

1
2
3
4
5
6
7
8
9
10
11
def zip(*iterable):
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)

Examples:

1
2
3
4
5
6
7
8
# python 2
zip(range(3), range(1, 10))
[(0, 1), (1, 2), (2, 3)]
# Python 3
zip(range(3), range(1, 10))
<zip object at 0x...>
list(range(3), range(1, 10))
[(0, 1), (1, 2), (2, 3)]


import(name, globals=None, locals=None, fromlist=(), level=0)

导入模块,import语句导入模块的时候就是调用了这个函数。其实想要以编程的方式导入模块,最好用importlib.import_module()

  • name: 模块名称。
  • globals/locals: potentially using the given globals and locals to determine how to interpret the name in a package context. 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.
  • fromlist: list or tuple, the names of objects or submodules that should be imported from the module given by name.
  • level: The level argument is used to determine whether to
    perform absolute or relative imports: 0 (python3 default value) is absolute, while a positive number is the number of parent directories to search relative to the current module.
1
2
spam = __import__('spam')  # <module 'spam' from '/home/...'>
spam = __import__('spam.ham') # <module 'spam' from '/home/...'>

注意: 当namepackage.module形式的时候,如果fromlist为空,返回的是最顶级的包 (即第一个点左边的包);如果fromlist不为空,则返回package.module指定的最终模块。

1
2
spam = __import__('spam.meat.ham')  # <module 'spam' from '...'>
ham = __import__('spam.meat.ham', fromlist=('xx',)) # <module 'ham' ...>