学习python的全局函数 2020/10/20

python中的全局函数

在Python3中全局函数如下所示

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

abs()
求绝对值

>>> a = -1
>>> abs(a)
1

all()
判断可迭代对象中的元素是否不为0,空,None,False,返回值是True,Flase。有任意一个元素为假,则为假
注:空的可迭代对象返回值True
类似于数学中的“且”

>>> all(['a', 'b', 'c', 'd'])  #列表元素都不为空或0
True
>>> all(['a', 'b', '', 'd'])   #列表存在一个为空的元素
False
>>>a ll([0, 1,2, 3])          #列表存在一个为0的元素
False 
>>> all([])             #空列表
True
>>> all(())             # 空元组
True

any()
判断可迭代对象不全为0,空,None,False,返回值是True,Flase。有任意一个元素为真,则就为真
类似于数学中的“或”

>>> any(['a', 'b', 'c', 'd'])  # 列表元素都不为空或0
True
>>> any(['a', 'b', '', 'd'])   # 列表元素至少有一个为真
True
>>> any([0, '', False])        # 列表元素全为0,'',false
False 
>>> any([]) # 空列表
False 
>>> any(()) # 空元组
False

ascii()
返回一个表示对象的字符串,如果参数是ascii字符,则返回一个字符串对象;如果参数不是ascii字符,则返回含有\u \U x的字符串对象

>>> ascii("python")
"'python'"
>>> ascii("穆瀚")
"'\\u7a46\\u701a'"
>>>

bin()
返回一个整型的二进制形式

>>> bin(11)
'0b1011'

bool()
将给定参数转换为布尔类型,如果没有参数,返回 False

>>> bool(0)
False
>>> bool(None)
False
>>> bool(False)
False
>>> bool(True)
True
>>> bool(123456)
True

breakpoint()

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

breakpoint(...)
    breakpoint(*args, **kws)

    Call sys.breakpointhook(*args, **kws).  sys.breakpointhook() must accept
    whatever arguments are passed.

    By default, this drops you into the pdb debugger.


关于模块内置函数断点的帮助:



断点(…)

断点(*args,**kws)



呼叫系统断点挂钩(*args,**kws)。系统断点挂钩()必须接受

不管通过什么论点。



默认情况下,这会将您放入pdb调试器。

bytearray()
返回一个新的字节数组。数组里的元素是可变的,并且每个元素的值范围: 0 <= x < 256
an iterable yielding integers in range(256)

>>> bytearray(b'')
bytearray(b'')
>>> bytearray(b'1,2,3')
bytearray(b'1,2,3')
>>> bytearray(b'[1,2,3]')
bytearray(b'[1,2,3]')
>>> bytearray([1,2,3])
bytearray(b'\x01\x02\x03')
>>> bytearray('穆瀚','utf-8')
bytearray(b'\xe7\xa9\x86\xe7\x80\x9a')

bytes()
返回一个新的字节对象,该对象是一个 0 <= x < 256 区间内的整数不可变序列。它是 bytearray 的不可变版本

>>> bytes()
b''
>>> bytes([1,2,3])
b'\x01\x02\x03'
>>> bytes('穆瀚','utf-8')
b'\xe7\xa9\x86\xe7\x80\x9a'
>>> bytes('name','utf-8')
b'name'

callable()
检查一个对象是否是可调用的。如果返回 True,object 仍然可能调用失败;但如果返回 False,调用对象 object 绝对不会成功。

>>> callable(0)
False
>>> def add(x,y):
...     return x+y
...
>>> callable(add)
True

chr()
返回当前整数对应的 ASCII 字符

>>> chr(10)
'\n'
>>> chr(97)
'a'
>>> chr(8888)
'⊸'
>>> chr(9999)
'✏'
>>> chr(9090)
'⎂'
>>> chr(0x1234)
'ሴ'

classmethod()
将方法转换为类方法。类方法将类作为隐式第一个参数接收,就像实例方法接收实例一样

>>> class A(object):
...     num = 10
...     def a1(self):
...             print(self)
...     @classmethod
...     def a2(cls):
...             print('a2')
...             print(cls.num)
...             cls().a1()
...
>>> A.a2()
a2
10
<__main__.A object at 0x0000011A196878B0>

compile()
能将一个字符串编译为字节代码

>>> str1 = "for i in range(0,4):print(i)"
>>> a = compile(str1,"","exec")
>>> print(a)
<code object <module> at 0x0000011A19712F50, file "", line 1>
>>> print(exec(a))
0
1
2
3
None

complex()
返回为real+imag*1j的复数

>>> print(complex(1,2))
(1+2j)
>>> print(complex())
0j
>>> print(complex(23))
(23+0j)

delattr()
用于删除对象属性。参数是一个对象和一个字符串。如果对象允许,函数将删除命名属性

>>> point1 = C()
>>> print("x=",point1.x)
x= 10
>>> print("y=",point1.y)
y= 11
>>> print("z=",point1.z)
z= 12
>>> delattr(C,"z")
>>> print("x=",point1.x)
x= 10
>>> print("y=",point1.y)
y= 11
>>> print("z=",point1.z)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'C' object has no attribute 'z'

dict ()
用于创建一个新的字典(dictionary),返回一个新的字典

>>> dict0 = dict()
>>> print('dict0:', dict0)
dict0: {
    
    }
>>>
>>> dict1 = dict({
    
    'name': 'li', 'age': 24})  
>>> print('dict1:', dict1)
dict1: {
    
    'name': 'li', 'age': 24}
>>>
>>> dict2 = dict(user='admin', password=123456)  
>>> print('dict2:', dict2)
dict2: {
    
    'user': 'admin', 'password': 123456}
>>>
>>> dict3 = dict([('student', 1), ('teacher', 2)])  
>>> print('dict3:', dict3)
dict3: {
    
    'student': 1, 'teacher': 2}
>>>
>>> dict4 = dict(zip(['a', 'A'], [3, 4]))  
>>> print('dict4:', dict4)
dict4: {
    
    'a': 3, 'A': 4}

dir()
返回结果列表按字母顺序排序,dir()函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。如果参数包含方法__dir__(),该方法将被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息

>>> dir(abs)
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']

divmod()
使用整数除法时,取两个(非复数)数作为参数并返回一对由其商和余数组成的数。对于混合操作数类型,应用二进制算术运算符的规则。对于整数,结果与(a//b,a%b)相同。对于浮点数,结果是(q,a%b),其中q通常是math.floor(a/b),但可能小于1在任何情况下,q*b+a%b都非常接近a,如果a%b为非零,则它具有与b相同的符号,且0<=abs(a%b)<abs(b)

>>> print(divmod(3,1))
(3, 0)
>>> print(divmod(5,2.1))
(2.0, 0.7999999999999998)
>>> print(divmod(7,-5))
(-2, -3)

enumerate()
返回枚举对象。iterable必须是序列、迭代器或其他支持迭代的对象。enumerate()返回的迭代器的__next__()方法返回一个元组,该元组包含一个计数(从开始时默认为0)和在iterable上迭代获得的值

>>> ls = "happy"
>>> print(list(enumerate(ls)))
[(0, 'h'), (1, 'a'), (2, 'p'), (3, 'p'), (4, 'y')]


>>> ls = ["A","B","C"]
>>> for i,element in enumerate(ls):
...     print(i,ls[i])
...
0 A
1 B
2 C

eval()
用来执行一个字符串表达式,并返回表达式的值

>>> a = 4
>>> b = 5
>>> print(eval('3*a'))
12
>>> print(eval('pow(3,3)'))
27
>>> print(eval('6+6'))
12
>>> print(eval('b-3')
2

exec()
能执行储存在字符串或文件中的 Python 语句,相比于 eval()函数,exec可以执行更复杂的 Python 代码

>>> exec ('print("你好,深圳!")')
你好,深圳!
>>>
>>> exec ("""                    
def sum(a,b):
    return a+b
print("a+b=%s"%sum(10,20))
""")
a+b=30

filter()
用于指定序列的过滤操作。以参数迭代器中的每个元素分别调用function函数,最后返回的迭代器包含调用结果为true的元素

>>> func =lambda x:x%2
>>> result = filter(func,[1,2,3,4,5,6])
>>> print(list(result))
[1, 3, 5]

float()
用于将整数和字符串转换成浮点数

>>> print(float(1))
1.0
>>> print(float(15))
15.0
>>> print(float(-15.3))
-15.3
>>> print(float('568'))
568.0

format()
用于字符串格式化输出,通过 {} 和 : 来代替以前的 % ,可通过 {} 和 : 来代替以前的 %

>>> print("名字:{name}, 年龄 {age}".format(name="穆瀚", age="18"))
名字:穆瀚, 年龄 18
>>> si = {
    
    "name": "穆瀚", "age": "18"} 
>>> print("名字:{name}, 年龄 {age}".format(**si))
名字:穆瀚, 年龄 18
>>> u_list = ['穆瀚', '18'] 
>>> print("名字:{0[0]}, 年龄 {0[1]}".format(u_list))
名字:穆瀚, 年龄 18

frozenset()
返回一个冻结的集合,冻结后集合不能再添加或删除任何元素

>>> print(frozenset())
frozenset()
>>> print(frozenset(range(0,15)))
frozenset({
    
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14})
>>> a = frozenset('Hello')
>>> print(a)
frozenset({
    
    'l', 'o', 'e', 'H'})
>>> print(a)
frozenset({
    
    'l', 'o', 'e', 'H'})
>>> a.add("0")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'

getattr()
用于返回一个对象属性值。名称必须是字符串。如果字符串是对象属性之一的名称,则结果是该属性的值

>>> class A(object):
...     num = 11
...
>>> a = A()
>>> print(getattr(a,'num'))
11
>>> print(getattr(a,'num2',30))
30
>>> print(getattr(a,'num2'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'num2'

globals()
返回全局变量,具体就是以字典类型返回当前位置的全部全局变量

>>> print(globals())
{
    
    '__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {
    
    }, '__builtins__': <module 'builtins' (built-in)>, 'si': {
    
    'name': '穆瀚', 'age': '18'}, 'a': <__main__.A object at 0x000002C86E510820>, 'A': <class '__main__.A'>}

hasattr()
用于判断用于判断对象是否包含对应的属性

>>> class C:
...     x=11
...     y=-6
...     z=1
...
>>> point1 = C()
>>> print(hasattr(point1,'x'))
True
>>> print(hasattr(point1,'y'))
True
>>> print(hasattr(point1,'z'))
True
>>> print(hasattr(point1,'abc'))
False

hash()
返回对象的哈希值(如果有)哈希值是整数。它们用于在字典查找期间快速比较字典键。比较相等的数值具有相同的哈希值(即使它们属于不同的类型,1和1.0也是如此)

>>> print(hash('hello'))
-4578479830251239883
>>> print(hash(str([1,2,3])))
-7845474558122420763
>>> print(hash(1))
1

help()
用于查看函数或模块用途的详细说明

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

abs(x, /)
    Return the absolute value of the argument.

hex()
用于将一个指定数字转换为 16 进制数

>>> hex(7)
'0x7'
>>> print(hex(12))
0xc

id()
返回对象的唯一标识符,标识符是一个整数,用于获取对象的内存地址

>>> id(abs)
1989786928128

input()
用于接受一个标准输入数据

>>> s = input('-->')
-->print(s)
>>> print(type(s))
<class 'str'>

int()
用于将一个字符串或数字转换为整型

>>> int(2)
2
>>> int(-9)
-9
>>> int(-9.4)
-9

isinstance()
用来判断对象是否是一个已知类型,和type()类似。但是有区别,type()不考虑继承关系,不认为子类是一种父类类型,而isinstance() 考虑继承关系,认为子类是一种父类类型

>>> a = 8
>>> isinstance(a,int)
True
>>> isinstance(a,float)
False
>>> isinstance(a,str)
False
>>> class A:
...     pass
...
>>> class B:
...
KeyboardInterrupt
>>> class B(A):
...     pass
...
>>> isinstance(A(),A)
True
>>> type(A()==A)
<class 'bool'>
>>> print(type(A()==A))
<class 'bool'>
>>> print(type(A())==A)
True
>>>
>>> isinstance(B(),A)
True

issubclass()
用来判断参数 class 是否是类型参数 classinfo 的子类。是返回True,否则返回False。注意,类被认为是其自身的子类

>>> class A:
...     pass
...
>>> class B(A):
...     pass
...
>>> isinstance(A(),A)
True
>>> print(type(A())==A)
True
>>> isinstance(B(),A)
True
>>> print(type(B())==A)
False

iter()
用来返回迭代器对象

>>> ls = [1,2,3,4]
>>> for i in iter(ls):
...     print(i)
...
1
2
3
4

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

>>> ls = [1,2,3,4]
>>> len(ls)
4

list()
用于将元组、区间(range)等转换为列表

>>> ls1 = {
    
    1,2,3,4}
>>> a = list(ls1)
>>> a
[1, 2, 3, 4]

locals()
会以字典类型返回当前位置的全部局部变量。对于函数,,方法,lambda 函式,,类,,以及实现了 call 方法的类实例,它都返回 True

>>> def adult(name):
...     age = 20
...     print(locals())
...
>>> adult("muhan")
{
    
    'name': 'muhan', 'age': 20}

map()
根据提供的函数对指定一个或多个序列做映射

>>> def cube(x):          
...     return x ** 3
...
>>> res = map(cube,[1,2,3])
>>> print(list(res))
[1, 8, 27]

max()
取传入的多个参数中的最大值,或者传入的可迭代对象元素中的最大值

>>> a = (1,2,3,4,5)
>>> max(a)
5

memoryview()
返回给定参数的内存查看对象。内存查看对象指对支持缓冲区协议的数据进行包装,在不需要复制对象基础上允许Python代码访问

>>> c = memoryview(bytearray("123456789","utf-8"))
>>> print(c[1])
50
>>> print(c[-1])
57
>>> print(c[1:5])
<memory at 0x000002A3C6E1A400>
>>>

min()
取传入的多个参数中的最小值,或者传入的可迭代对象元素中的最小值

>>> a = (1,2,3,4,5)
>>> min(a)
1

next()
用于返回迭代器的下一个项目。通过调用迭代器的__next__()方法从迭代器中检索下一个项。如果给定了默认值,则在迭代器耗尽时返回该值,否则将引发StopIteration

>>> while True:
...     try:
...             x = next(a)
...             print(x)
...     except StopIteration:
...             break
...
1
2
3
4
>>> class A:
...     pass
...
>>> a = A()
>>> a.name = "mu"
>>> b = object()
>>> b.name = "wang"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'name'

oct()
将一个整数转换成前缀为“0o”的八进制字符串

>>> oct(10)
'0o12'
>>> oct(59)
'0o73'
>>> oct(-11)
'-0o13'

open()
用来打开文件

>>> a1=open("testA.txt","w")
>>> a1.write("python")
6
>>> a1.close()
>>> a2=open("testA.txt","r")
>>> content=a2.read()
>>> str = content.replace(" ","")
>>> a3 = open("textB.txt","w")
>>> a3.write(str)
6
>>> a2.close()
>>> a3.close()

ord()
以一个字符串(Unicode 字符)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值

>>> ord("a")
97
>>> ord("0")
48
>>> ord("-")
45

pow()
返回x的y次方

>>> pow(2,3)
8
>>> pow(15,3)
3375
>>> pow(10,7)
10000000

print()
打印输出

>>> a = [1,2]
>>> b = 'hello'
>>> c = '你好' #可以直接输出中文
>>> print(a,b,c,end="\n") #默认换行
[1, 2] hello 你好
>>> print(a,b,c,end="123456") #结尾123456
[1, 2] hello 你好123456>>> print("www","baidu","com",sep=".")
www.baidu.com
>>>

property()
用于新式类中返回属性值

class Parrot(object):
    def __init__(self):
        self._voltage = 100000
 
    @property
    def voltage(self):
        """Get the current voltage."""
        return self._voltage

range()
用于可创建一个整数列表,一般用于for循环

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4

repr()
控制该函数为其实例返回的内容

>>> print(repr((1,2))) 
(1, 2)
>>> print(type(repr((1,2))))
<class 'str'>
>>>
>>> print(repr([1,2])) 
[1, 2]
>>> print(type(repr([1,2])))
<class 'str'>
>>>
>>> print(repr({
    
    1:2,'name':5})) 
{
    
    1: 2, 'name': 5}
>>> print(type(repr({
    
    1:2,'name':5})))
<class 'str'>
>>>
>>> print(repr('?')) 
'?'
>>> print(type(repr("?")))
<class 'str'>
>>>
>>> print(repr(set([1,1,2,3]))) 
{
    
    1, 2, 3}
>>> print(type(repr(set([1,1,2,3]))))
<class 'str'>

reversed()
返回一个反转的迭代器(元组、列表、字符串、range)

>>> seqTuple = ('H', 'e', 'l', 'l', 'o') 
>>> print(list(reversed(seqTuple)))
['o', 'l', 'l', 'e', 'H']
>>> seqList = [7, 8, 4, 5, 6]  
>>> print(list(reversed(seqList)))
[6, 5, 4, 8, 7]
>>> seqString = 'HelloWorld' 
>>> print(list(reversed(seqString)))
['d', 'l', 'r', 'o', 'W', 'o', 'l', 'l', 'e', 'H']
>>> seqRange = range(1, 8)    
>>> print(list(reversed(seqRange)))
[7, 6, 5, 4, 3, 2, 1]

round()
返回浮点数number的四舍五入值

>>> print ("round(60.232456) : ", round(60.232456))
round(60.232456) :  60
>>> print ("round(45.659,1) : ", round(45.659,1))
round(45.659,1) :  45.7
>>> print ("round(44.234, 2) : ", round(44.234, 2))
round(44.234, 2) :  44.23

set()
返回一个新的无序不重复元素集合

>>> set1 = set([1,2,3,3,4])
>>> set2 = set([5,8,9,4])
>>> print(set1,set2) 
{
    
    1, 2, 3, 4} {
    
    8, 9, 4, 5}
>>> print(set1&set2) 
{
    
    4}
>>> print(set1|set2) 
{
    
    1, 2, 3, 4, 5, 8, 9}
>>> print(set1-set2) 
{
    
    1, 2, 3}

setattr()
对应函数getattr(),用于设置属性值

>>> class A(object):
...     aaa = 2
...
>>> a = A()
>>> print(getattr(a,"aaa"))
2
>>> setattr(a,"aaa",4)
>>> print(a.aaa)
4

slice()
实现切片对象,主要用在切片操作函数里的参数传递

>>> print(slice(4))
slice(None, 4, None)
>>> arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> tup = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> print(arr[slice(4)])
[0, 1, 2, 3]
>>> print(tup[slice(4)])
(0, 1, 2, 3)

sorted()
对所有可迭代的对象进行排序操作

>>> a = [5,7,6,3,4,1,2]
>>> b = sorted(a)
>>> a
[5, 7, 6, 3, 4, 1, 2]
>>> b
[1, 2, 3, 4, 5, 6, 7]

staticmethod()
用于返回函数的静态方法

>>> class B(object):
...     @staticmethod
...     def f():
...             print("python")
...
>>> B.f()
python
>>> cobj = B()
>>> cobj.f()
python

str()
将对象转化为字符串

>>> a = "python"
>>> str(a)
'python'
>>> age = 24
>>> mes="I'm " + str(age) + " years old"
>>> print(mes)
I'm 24 years old
>>>

sum()
用于对序列求和计算

>>> a = [1,2]
>>> b = (1,2,3)
>>> c = (1,2,3,4,5)
>>> d = {
    
    1:'name',2:'age'}
>>> print(sum(a))
3
>>> print(sum(b))
6
>>> print(sum(c,5))
20
>>> print(sum(d)) 
3

super()
用于调用父类(超类)的一个方法

class FooParent(object):
    def __init__(self):
        self.parent = 'I\'m the parent.'
        print('Parent')
    def bar(self, message):
        print("%s from Parent" % message)
class FooChild(FooParent):
    def __init__(self):
        super(FooChild, self).__init__()
        print('Child')
    def bar(self, message):
        super(FooChild, self).bar(message)
        print('Child bar fuction')
        print(self.parent)
if __name__ == '__main__':
    fooChild = FooChild()
    fooChild.bar('HelloWorld')



输出
Parent
Child
HelloWorld from Parent
Child bar fuction
I'm the parent.

tuple()
用于将列表、区间(range)等转换为元组

>>> a = [1,2] #list
>>> b = {
    
    "1":2,"3":3} #dict
>>> c = {
    
    1,2,3,3}  #set
>>> d = range(2,10,2) #range
>>> print(tuple(a))
(1, 2)
>>> print(tuple(b))
('1', '3')
>>> print(tuple(c))
(1, 2, 3)
>>> print(tuple(d))
(2, 4, 6, 8)

type()
只传第一个参数则返回对象的类型

>>> a = [1,2,3,4]
>>> b = 12
>>> c = "python"
>>> d = {
    
    "name":"muhan"}
>>> class XXX(object):
...     e = 1
...
>>> XXX = type("XXX",(object,),dict(e=1))
>>> print(type(a))
<class 'list'>
>>> print(type(b))
<class 'int'>
>>> print(type(c))
<class 'str'>
>>> print(type(d))
<class 'dict'>
>>> print((type(b) ==int )) #比较
True
>>> print(XXX)
<class '__main__.XXX'>

vars()
返回模块、类、实例或具有dict属性的任何其他对象的dict属性

>>> print(vars())
{
    
    '__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {
    
    }, '__builtins__': <module 'builtins' (built-in)>, 'a': [1, 2, 3, 4], 'age': 24, 'mes': "I'm 24 years old", 'b': 12, 'c': 'python', 'd': {
    
    'name': 'muhan'}, 'XXX': <class '__main__.XXX'>}
>>> class helloworld:
...     a = 1
...
>>> print(vars(helloworld))
{
    
    '__module__': '__main__', 'a': 1, '__dict__': <attribute '__dict__' of 'helloworld' objects>, '__weakref__': <attribute '__weakref__' of 'helloworld' objects>, '__doc__': None}

zip()
从参数中的多个迭代器取元素组成一个新的迭代器,长度由最短的参数决定

>>> a = ('a','b','c','d','e') 
>>> b = (1,2,3,4,5) 
>>> ob = zip(a,b) 
>>> print(ob) 
<zip object at 0x000001AE8F3B5840>
>>> print(dict(ob)) 
{
    
    'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

猜你喜欢

转载自blog.csdn.net/MHguitar/article/details/109173426