python内置函数大全(含使用用例)

    内置函数    
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()

返回数字的绝对值。参数可以是整数或浮点数

all(iterable)

如果集合中所有元素是true或集合为空集合,返回True

any(iterable)

如果集合中有一项元素是true,返回True;空集合为False

#all and any
lst = []
print(lst, '-all():', all(lst)) #True
print(lst, '-any():', any(lst)) #False

lst0 = ['']
print(lst0, '-all():', all(lst0)) #False
print(lst0, '-any():', any(lst0)) #False

lst1 = [None]
print(lst1, '-all():', all(lst1)) #False
print(lst1, '-any():', any(lst1)) #False

lst2 = [0]
print(lst2, '-all():', all(lst2)) #False
print(lst2, '-any():', any(lst2)) #False

lst3 = [1, None, 'a']
print(lst3, '-all():', all(lst3)) #False
print(lst3, '-any():', any(lst3)) #True

lst4 = [1, '0', 'a']
print(lst4, '-all():', all(lst4)) #True
print(lst4, '-any():', any(lst4)) #True

lst5 = [False, '0', 'a']
print(lst5, '-all():', all(lst5)) #False
print(lst5, '-any():', any(lst5)) #True

ascii(object)

ascii() 函数类似 repr() 函数, 返回一个表示对象的字符串, 但是对于字符串中的非 ASCII 字符则返回通过 repr() 函数使用 \x, \u 或 \U 编码的字符

bin(x)

将整数转换为前缀为“0b”的二进制字符串。如果参数'x'不是int对象,则必须定义一个__index__()方法返回整数:

#bin()
print(bin(255)) #0b11111111
print(bin(-255)) #-0b11111111

bool(x)

返回一个布尔值,即True或者之一False

#bool()
bool(0) #False
bool(1) #True
bool(-1) #True
bool(2) #True
bool(0.0) #False
bool(1.0) #True
bool('') #False
bool('a') #True
bool(None) #False

breakpoint(* args,_** kws _)

版本3.7中的新功能,此函数会将您置于调用站点的调试器中。

bytearray([ _source _[,_encoding _[,_errors _] ] ] )

返回一个新的字节数组。由于1Byte = 8Bit,所以0<=数组每一项<256,返回值是一个可变序列。

  • 如果source参数是一个字符串,您还必须提供编码(和可选的, 错误)参数,调用字符串的encode()方法将字符串转换成字节数组;
  • 如果source参数是一个整数,返回该整数长度的被\x00填充的字节数组。
  • 如果source参数是实现了buffer接口的Object对象,则使用只读方式将字节读取到字节数组后返回。
  • 如果source参数是可迭代的,则迭代的每一项必须在[0, 255]之间
  • 如果没有参数,则会创建一个大小为0的数组。

bytes([ _source _[,_encoding _[,_errors _] ] ] )

与bytearray相似,是字节组成的有序的不可变序列

callable(对象

判断对象参数是否可被调用(可被调用指的是对象能否使用()括号的方法调用

  • 如果object参数显示为可调用,则返回True,否则返回False。
  • 如果返回true,调用仍然可能失败,
  • 如果为False,则调用对象将永远不会成功。
  • 类对象都是可被调用对象,类的实例对象是否可调用对象,取决于类是否定义了call方法。

版本3.2中的新功能此功能首先在Python 3.0中删除,然后在Python 3.2中恢复。

# callable()
callable(1) # False
callable(str) # True
class classA:
    pass
callable(classA) # True
instanceA = classA()
callable(instanceA) # False
class classB:
    def __call__(self):
        print('this is __call__ method')
callable(classB) # True
instanceB = classB()
callable(instanceB) # True

chr(_i _)

返回表示Unicode代码点为整数i的字符的字符串。例如,chr(97)返回字符串'a',与ord()函数相反,参数的有效范围是0到1,114,111(基数为16的0x10FFFF)。

@classmethod

将方法转换为类方法。

类方法接收类作为隐式的第一个参数,就像实例方法接收实例一样。要声明一个类方法,请使用此习语:

compile(sourcefilenamemodeflags = 0dontinherit = Falseoptimize = -1 _)

代码编译为代码或AST对象。代码对象可以由exec()或执行eval()source可以是普通字符串,字节字符串或AST对象。

class complex([ _real _[,_imag _] ])

返回值为real + imag * 1j的复数或将字符串或数字转换为复数。如果第一个参数是一个字符串,它将被解释为一个复数,并且必须在没有第二个参数的情况下调用该函数。第二个参数永远不能是字符串。每个参数可以是任何数字类型(包括复数)。如果IMAG被省略,默认为零,并且构造用作数字转换等int和float。如果省略两个参数,则返回 0j

getattr(对象名称hasattr(对象名称setattr(对象名称delattr(对象名称

getattr() hasattr() setattr() delattr()是一组对对象属性操作的内置函数

  • getattr():获取对象的属性
  • hasattr():检查对象是否有某属性
  • setattr():设置对象的属性
  • delattr():删除对象的属性
#getattr() hasattr() setattr() delattr()
class classX:
    attr1 = 'classX`s attr1'
    def __init__(self, attr2):
        self.attr2 = attr2
instanceX = classX('self.attr2=attr2')

#getattr()
getattr(instanceX, 'attr2', 'not found attr2') # 'self.attr2=attr2'

#hasattr()
hasattr(instanceX, 'attr1') # True

#setattr()
getattr(instanceX, 'attr3', 'not found attr3') # 'not found attr3'
setattr(instanceX, 'attr3', 'attr3`s value')
instanceX.attr3 # 'attr3`s value'
getattr(instanceX, 'attr3', 'not found attr3') # 'attr3`s value'

#delattr()
delattr(instanceX, 'attr3')
getattr(instanceX, 'attr3', 'not found attr3') # 'not found attr3'
instanceX.attr3 # AttributeError: 'classX' object has no attribute 'attr3'

dict()

创建一个字典。

#dict()
dict() #{}
dict({'key1':'val1', 'key2':'val2'}) # {'key1': 'val1', 'key2': 'val2'}
dict(key1='val1', key2='val2') # {'key1': 'val1', 'key2': 'val2'}
dict([('key1', 'val1'), ('key2', 'val2'), ('key3', 'val3')]) # {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}
dict([('key1', 'val1'), ('key2', 'val2'), ('key2', 'val3')]) # {'key1': 'val1', 'key2': 'val3'}

dir([ 对象])

  • 如果 dir() 没有参数,则返回当前作用域中的名称列表;否则,返回给定 object参数 的一个已排序的属性名称列表。
  • 如果对象提供了 dir() 方法,则它将会被使用;否则,使用默认的 dir() 逻辑,并返回。
  • 结果列表按字母顺序排序。
  • 当参数是类时,元类属性不在结果列表中。

divmod(ab

将两个数作为参数,并在使用整数除法时返回由商和余数组成的一对数

>>> divmod(-10, 3)
(-4, 2)
>>> divmod(9, 3)
(3, 0)
>>> divmod(-10, 3)
(-4, 2)

enumerate(iterablestart = 0

  • enumerate是枚举、列举的意思
  • 对于一个可迭代的(iterable)/可遍历的对象(如列表、字符串),enumerate将其组成一个索引序列,利用它可以同时获得索引和值
  • enumerate多用于在for循环中得到计数
>>> lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> map = {}
>>>
>>> for index, item in enumerate(lst):
...     map.__setitem__(index, item)
>>> print(map)
{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g'}

eval(表达式globals = Nonelocals = None

将字符串string对象转化为有效的表达式参与求值运算返回计算结果

参数是一个字符串和可选的全局变量和本地变量。 globals如果存在,必须是字典对象。locals如果存在,则可以是任何Map对象。

>>> eval('1+2')
3
>>> nums = eval('range(10)')
>>>
>>> for item in nums:
...     print(item)
...
0
1
2
3
4
5
6
7
8
9

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

exec语句用来执行储存在字符串或文件中的Python语句

此函数支持Python代码的动态执行。object必须是字符串或代码对象。如果它是一个字符串,则将该字符串解析为一组Python语句,然后执行该语句(除非发生语法错误)。如果是代码对象,则只执行它。在所有情况下,执行的代码应该作为文件输入有效(请参见“参考手册”中的“文件输入”部分)。返回值是None

>>> exec("""for i in range(5):
...             print("item: %d" % i)""")
item: 0
item: 1
item: 2
item: 3
item: 4

filter(功能可迭代

filter函数用于过滤序列

filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素

>>> # filter()
>>> def isOdd(x):
...     return x % 2 == 1
>>> list(filter(isOdd, range(10)))
[1, 3, 5, 7, 9]

format(value [, formatspec_])

格式化数值

>>> format(123456) #换成字符串
'123456'
>>> format(128, '<20') #左对齐
'128                 '
>>> format(128, '<20b') #转换成二进制后左对齐
'10000000            '
>>> format(128, 'b>20') #右对齐后填充b
'bbbbbbbbbbbbbbbbb128'
>>> format(128, '>20') #右对齐
'                 128'
>>> format(-128, '=20') #拆分负号和数字分别左右对齐
'-                128'
>>> format(128, '^20') #居中对齐
'        128         '
>>> format(1234567, ',') #千位分隔符
'1,234,567'
>>> format(8, 'b') #转换成二进制
'1000'
>>> format(99, 'c') #转换unicode成字符
'c'
>>> format(0b1000, 'd') # 转换成十进制
'8'
>>> format(64,'o') #转换成8进制
'100'
>>> format(4560,'x') #转换成16进制 小写字母表示
'11d0'
>>> format(4560,'X') #转换成16进制 大写字母表示
'11D0'
>>> format(1314521,'e') #科学计数法,默认保留小数点后6位
'1.314521e+06'
>>> format(1314521,'0.3e') #科学计数法,保留小数点后3位
'1.315e+06'
>>> format(1314521,'0.3E') #科学计数法,保留小数点后3位
'1.315E+06'
>>> format(1314521,'f') #小数点计数法,默认保留小数点后6位
'1314521.000000'
>>> format(1314521,'0.3f')#小数点计数法,保留小数点后3位
'1314521.000'

class frozenset([iterable])

class set([iterable])

class list([iterable])

class tuple([iterable])

class dict([iterable])

  • frozenset()返回一个冻结的集合,冻结后集合不能再添加或删除任何元素
  • set()返回可变,无序不重复的集合
>>> #frozenset() set()
...
>>> aset = set('abdfg')
>>> aset.add('h')
>>> print(aset)
{'f', 'a', 'g', 'd', 'b', 'h'}
>>> aset2 = set([1,2,3,4,2,4,5])
>>> print(aset2)
{1, 2, 3, 4, 5}
>>> fset = frozenset('abcef')
>>> print(fset)
frozenset({'f', 'c', 'a', 'e', 'b'})
>>> fset.add('h')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'
>>> aset&fset #交集
{'f', 'a', 'b'}
>>> aset|fset #并集
{'f', 'c', 'a', 'e', 'g', 'd', 'b', 'h'}
>>> aset-fset #差集 aset有的,fset没有的
{'g', 'h', 'd'}
>>> aset^fset #对称差集, 单独存在于两个集合,对方不存在的
{'g', 'c', 'd', 'h', 'e'}
  • list()返回可变有序可重复的集合
  • tuple()返回不可变的序列
>>> list(range(6))
[0, 1, 2, 3, 4, 5]
>>> list(['a', 'b', 'c'])
['a', 'b', 'c']
>>> list('中国人民')
['中', '国', '人', '民']
>>> list({'key1':'val1', 'key2':'val2'})
['key1', 'key2']
>>> tuple(range(6))
(0, 1, 2, 3, 4, 5)
>>> tuple(['a', 'b', 'c'])
('a', 'b', 'c')
>>> tuple('中国人民')
('中', '国', '人', '民')
>>> tuple({'key1':'val1', 'key2':'val2'})
('key1', 'key2')
  • dict()返回一个键值对序列(参见dict函数说明)

globals()

locals()

  • globals()返回一个全局变量的字典,包括所有导入的变量。
  • locals()返回一个局部变量的字典

hash(对象

返回对象的哈希值。

>>> hash(range(6))
8834509408445966602

注意

对于具有自定义hash()方法的对象,请注意hash()根据主机的位宽截断返回值。

help(对象

调用内置帮助系统。(此函数用于交互式使用。)如果未给出参数,则帮助系统将在解释器控制台上启动。如果参数是字符串,则查找字符串作为模块,函数,类,方法,关键字或文档主题的名称,并在控制台上打印帮助页面。如果参数是任何其他类型的对象,则会生成对象的帮助页面。

>>> help(print)
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

>>> help('print')
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

hex(x

将整数转换为带有前缀“0x”的小写十六进制字符串。如果x不是Python int对象,则必须定义一个__index__()返回整数的方法。

>>> hex(16)
'0x10'
>>> hex(16.0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer
>>> class classZ:
...     def __index__(self):
...         return 16
...
>>> instanceZ = classZ()
>>> hex(instanceZ)
'0x10'

注意

要获取float的十六进制字符串表示形式,请使用该float.hex()方法。

id(对象

返回代表对象的“身份”的一个整数,在该生命周期内保证该对象是唯一且恒定的。但在不重合的生命周期里,可能会出现相同的id值。也可以理解为对象的地址

input([ 提示 ])

接收任意输入,将所有输入默认为字符串处理,并返回字符串类型

class int(x = 0

class int(xbase = 10

返回由数字或字符串x构造的整数对象,如果没有给出参数,则返回0。如果x定义__int__(),则int(x)返回x.__int__()。如果x定义__trunc__(),则返回x.__trunc__()。对于浮点数,这将截断为零。

如果X不是数字或如果base给出,则X必须是一个字符串。

>>> int()
0
>>> int(3e3)
3000
>>> int('100', 2)
4
>>> int('0x10', 16)
16

isinstance(objectclassinfo

type(object

>>> isinstance(2, int)
True
>>> type(2) == int
True
>>> isinstance(2.0, float)
True
>>> type(2.0) == float
True
>>> isinstance(True, bool)
True
>>> type(True) == bool
True
>>> isinstance('2', str)
True
>>> type('2') == str
True
>>>
>>> class classY:
...     pass
...
>>> class classYY(classY):
...     pass
...
>>> instanceY = classY()
>>> instanceYY = classYY()
>>> isinstance(instanceY, classY)
True
>>> type(instanceY) == classY
True
>>> isinstance(instanceYY, classYY)
True
>>> type(instanceYY) == classYY
True
>>> isinstance(instanceYY, classY)
True
>>> type(instanceYY) == classY
False
  • isinstance():如果object参数是classinfo 参数的实例,或者是classinfo子类的实例,则返回true ,否则返回false
  • type(): 直接返回对象的类型

issubclass(classclassinfo

如果classclassinfo的子类,则返回true 。

>>> class father:
...     pass
...
>>> class child(father):
...     pass
...
>>> issubclass(child, father)
True

iter(object [, sentinel ] )

返回一个迭代器对象。

  • object -- 支持迭代的集合对象。
  • sentinel -- 如果传递了第二个参数,则参数 object 必须是一个可调用的对象(如,函数),此时,iter 创建了一个迭代器对象,每次调用这个迭代器对象的__next__()方法时,都会调用 object。
>>> ll = iter(range(10))
>>> next(ll)
0
>>> next(ll)
1
>>> next(ll)
2

len(s

返回对象的长度(项数)。参数可以是序列(例如字符串,字节,元组,列表或范围)或集合(例如字典,集合或冻结集合)。

>>> len(range(10))
10
>>> len('abcde')
5
>>> len(bytearray(30))
30

map(functioniterable……

返回一个迭代器,它将function应用于iterable每个项,从而产生结果。如果传递了其他iterable参数,则 function必须采用那么多参数,并且并行地应用于所有迭代的项。

>>> def f(x):
...     return x * x
...
>>> ll = range(1, 11)
>>> newll = map(f, ll)
>>> print(list(newll))
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

max(iterable*[,key,default]

max(arg1arg2,_* args _ [, key]

min(iterable*[,key,default]

min(arg1arg2,_* args _ [, key]

返回可迭代中的最大/小项或两个或多个参数中的最大/小项。

>>> nums = range(1, 11)
>>> max(nums)
10
>>> min(nums)
1

memoryview(obj

返回内存查看对象

next(iterator [,default])

通过调用iterator 的__next__()方法,获取**iterator **的下一项。如果给定default,则在下一项不存在时返回。

>>> nums = iter(range(5))
>>> next(nums, 'is end')
0
>>> next(nums, 'is end')
1
>>> next(nums, 'is end')
2
>>> next(nums, 'is end')
3
>>> next(nums, 'is end')
4
>>> next(nums, 'is end')
'is end'

oct(x

将整数转换为前缀为“0o”的八进制字符串。如果x不是Python int对象,则必须定义一个__index__()返回整数的方法。

>>> oct(8)
'0o10'
>>> oct(-56)
'-0o70'
>>> '%#o' % 10, '%o' % 10
('0o12', '12')
>>> format(10, '#o'), format(10, 'o')
('0o12', '12')
>>> f'{10:#o}', f'{10:o}'
('0o12', '12')

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None

打开文件并返回相应的file对象。如果无法打开文件,则引发OSError

  • file———是一个类似路径的对象

  • mode———是一个可选字符串,用于指定打开文件的模式,可用模式为:

字符 含义
'r' 只读(默认)
'w' 打开写入,先截断文件
'x' 打开以进行独占创建,如果文件已存在则失败
'a' 打开以进行写入,如果存在则附加到文件的末尾
'b' 二进制模式
't' 文字模式(默认)
'+' 打开磁盘文件进行更新(读写)

ord(c

返回字符的Unicode码。

>>> ord('a')
97

pow(x, y [, z ]

返回x^y,如果z存在返回x^y%z

>>> pow(2, 4)
16
>>> pow(2, 4, 5)
1

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False

打印输出

  • objects -- 复数,表示可以一次输出多个对象。输出多个对象时,需要用** , **分隔。
  • sep -- 用来间隔多个对象,默认值是一个空格。
  • end -- 用来设定以什么结尾。默认值是换行符 \n,我们可以换成其他字符串。
  • file -- 要写入的文件对象。
>>> print('abc', 'def', sep=";", end="!!!")
abc;def!!!>>>

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

property()函数中的三个函数分别对应的是获取属性的方法、设置属性的方法以及删除属性的方法。

>>> class classT:
...     def __init__(self, attrValue):
...         self.attr = attrValue
...     def setAttr(self, attrValue):
...         self.attr = attrValue
...     def getAttr(self):
...         return self.attr
...     def delAttr(self):
...         del self.attr
...     do = property(getAttr, setAttr, delAttr)
...
>>> instanceT = classT(20)
>>> instanceT.do
20
>>> instanceT.do = 40
>>> del instanceT.do
>>> instanceT.do
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in getAttr
AttributeError: 'classT' object has no attribute 'attr'

range(stop

range(start, stop[, step]

实际上,它不是一个函数,而是一个不可变的序列类型。

  • start: 计数开始,包含start;
  • stop: 计数结束,不包括 stop;
  • step:步长
>>> range(5)
range(0, 5)
>>> range(2, 5)
range(2, 5)
>>> range(1, 10, 2)
range(1, 10, 2)

repr(object

str(object=''

str(object=b'', encoding='utf-8', errors='strict'

object参数转换为各种形式的字符串,与str()函数相似

  • repr() 转化为供解释器读取的形式
  • str()转化为适于人阅读的形式
>>> s = 'hello world \'你好,世界\''
>>> repr(s)
'"hello world \'你好,世界\'"'
>>> str(s)
"hello world '你好,世界'"
>>> str(b"hello world '\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c'", encoding = "utf8")
"hello world '你好,世界'"

reversed(seq

反转一个序列对象,将其元素从后向前颠倒构建成一个新的迭代器后返回,如果参数seq不是序列对象,则必须定义一个__reversed__()方法

>>> nums = range(10)
>>> new_nums = reversed(nums)
>>> print(list(new_nums))
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

round(number[, ndigits]

小返回浮点数x的四舍五入值

>>> round(1, 3)
1
>>> round(1.2352, 1)
1.2
>>> round(1.2352, 2)
1.24
>>> round(1.2352, 3)
1.235

class slice(stop

class slice(start, stop[, step]

返回表示由指定的索引集的切片对象。start和step默认是None。切片对象主要是对序列对象进行切片取元素

>>> nums = list(range(10))
>>> s = slice(2, 7, 2)
>>> nums[s]
[2, 4, 6]

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

iterable中的项返回一个新的排序列表。

有两个可选参数,必须指定为关键字参数。

key指定一个参数的函数,用于从每个列表元素中提取比较键:key=str.lower。默认值为None (直接比较元素)。

reverse是一个布尔值。如果设置为True,则对列表元素进行排序,就好像每个比较都已反转一样。

>>> s = [3,2,1,34,23,9]
>>> sorted(s)
[1, 2, 3, 9, 23, 34]
>>> students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
>>> sorted(students, key=lambda s: s[2])
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

@staticmethod

将方法转换为静态方法(类方法)。

静态方法不会接收隐式的第一个参数。要声明静态方法,请使用此用法:

>>> class classS:
...     @staticmethod
...     def fun():
...         print('this is static method')
...
>>> classS.fun()
this is static method

sum(iterable[, start])

求和计算

>>> nums = list(range(10))
>>> nums
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> sum(nums)
45
>>> sum(nums, 5)
50

super([type[, object-or-type]])

super([ _type _[,_object-or-type _] ] )

返回一个代理对象, 这个对象负责将方法调用分配给第一个参数的一个父类或者同辈的类去完成。

第一个参数的mro属性决定了搜索的顺序, super指的的是 MRO(Method Resolution Order) 中的下一个类, 而不一定是父类!

super()和getattr() 都使用mro属性来解析搜索顺序, mro实际上是一个只读的元组.

#super
class Root:
    def root_method(self):
        print('this is root_method')
    def r_a_method(self):
        print('this is root r_a_method')

class A(Root):
    def a_method(self):
        print('this is a_method')
    def r_a_method(self):
        print('this is a r_a_method')

class B(Root):
    def b_method(self):
        print('this is b_method')

class C(A, B):
    def c_method(self):
        super().a_method()
        super().r_a_method()
instanceC = C()
instanceC.c_method()

vars([object])

返回对象object的属性和属性值的字典对象

>>> class classV:
...     a = 1
...     def v_m(self):
...         return 2
...
>>> vars(classV)
mappingproxy({'__module__': '__main__', 'a': 1, 'v_m': <function classV.v_m at 0x00000000028400D0>, '__dict__': <attribute '__dict__' of 'classV' objects>, '__weakref__': <attribute '__weakref__' of 'classV' objects>, '__doc__': None})
>>> instanceV = classV()
>>> vars(instanceV)
{}

zip(*iterables)

创建一个聚合每个迭代器元素的tuple迭代器。

>>> tuple(zip())
()
>>> l1 = [1,3,5,7,9]
>>> l2 = [2,4,6,8,10]
>>> tuple(zip(l1,l2))
((1, 2), (3, 4), (5, 6), (7, 8), (9, 10))
>>> l3 = ['a','b','c','d','e','f']
>>> tuple(zip(l1,l2,l3))
((1, 2, 'a'), (3, 4, 'b'), (5, 6, 'c'), (7, 8, 'd'), (9, 10, 'e'))

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

  1. 函数功能用于动态的导入模块,主要用于反射或者延迟加载模块。

  2. import(module)相当于import module

版权声明:本文为博主原创文章,未经博主允许不得转载  https://mp.csdn.net/postedit/81662806

猜你喜欢

转载自blog.csdn.net/laokaikai/article/details/81662806