内置函数 | ||||
abs() | delattr() | hash() | memoryview() | set() |
all() | dict() | help() | min() | setattr() |
any() | dir() | hex() | next() | slice() |
ascii() | divmod() | | object() | sorted() |
bin() | enumerate() | input() | oct() | staticmethod() |
bool() | eval() | int() | open() | str() |
breakpoint() | exec() | isinstance() | ord() | sum() |
bytearray() | | pow() | pow() | super() |
bytes() | float() | iter() | print() | tuple() |
callable() | format() | en() | property() | type() |
chr() | frozenset() | list() | range() | vars() |
classmethod() | getattr() | locals() | repr() | zip() |
compile() | globals() | map() | reversed() | __import__() |
complex() | hasattr() | max() | round() | |
1.数学运算类函数
1)计算数值的绝对值:abs()
1 print(abs(-15))
2
3 -----输出结果----
4 15
2)返回两个数的商和余数:divmod()
1 print(divmod(13,5))
2
3 ------输出结果------
4 (2,3)
3)返回所有参数中元素的最大值或者返回可迭代对象中元素的最大值:max()
1 print(max(1,2,3)) #取三个数中的最大者
2
3 print(max('123')) #取可迭代对象中的最大者
4
5 print(max(-2,-1,0,key=abs)) #把-2,-1,0依次传给abs的参数,然后把abs的结果返回给key,max依次比较key的大小
6
7 -------输出结果-------
8 -2
4)返回所有参数中元素的最小值或者返回可迭代对象中元素的最小值:min()
1 print(min(1,2,3)) #取三个数中的最小者
2
3 print(min('123')) #取可迭代对象中的最小者
4
5 print(min(-2,-1,0,key=abs)) #把-2,-1,0依次传给abs的参数,然后把abs的结果返回给key,max依次比较key的大小
6
7 -------输出结果-----
8 1
9 1
10 0
5)返回两个数值的幂运算值或者其与指定值的余数:pow()
1 print(pow(2,4)) #2的4次幂
2
3 print(pow(2,4,3)) #2的4次幂,然后除以3的余数 1
4
5 ------输出结果-----
6 16
7 1
6)对浮点数进行四舍五入:round()
1 print(round(2.563,1)) #2.563四舍五入,精度为1
2
3 print(round(2.561654132,5)) #2.561654132四舍五入,精度为5
4
5 --------输出结果------
6 2.6
7 2.56165
7)对参数类型为数值的可迭代对象中的每个元素求和:sum()
1 print(sum((1,2,3,4,5,6))) #对可迭代对象进行求和
2
3 print(sum((1,2,3,4,5,6),16)) #可迭代对象的和与'start'的和
4
5 --------输出结果-----
6 21
7 37
2.类型转换类函数
1)根据传入的参数的值返回布尔值:bool()
1 print(bool()) #不传递参数,返回False
2 print(bool(0))
3 print(bool(''))
4 print(bool(())) # 0,'',()等为值的布尔值为False
5
6 print(bool(2))
7
8 ------输出结果------
9 False
10 False
11 False
12 False
13 True
2)根据传入的参数值创建一个新的整数值:int()
1 print(int()) #不传递参数时,结果为0
2
3 print(int(1.8)) #向下取整
4
5 print(int('12')) #根据字符串类型创建整型
6
7 -------输出结果------
8 0
9 1
10 12
3)根据传入的参数值创建一个新的浮点数值:float()
1 print(float()) #不传递参数时,结果为0.0
2
3 print(float(1))
4
5 print(float('12')) #根据字符串类型创建浮点值
6
7 -------输出结果------
8 0.0
9 1.0
10 12.0
4)根据传入的参数值创建一个新的复数值:complex()
1 print(complex()) #不传递参数时,结果为0j
2
3 print(complex(1))
4
5 print(complex(1,3)) #1为实数部分,3为虚数部分
6
7 print(complex('12')) #根据字符串类型创建复数
8
9 print(complex('1+2j'))
10
11 ------输出结果-----
12 0j
13 (1+0j)
14 (1+3j)
15 (12+0j)
16 (1+2j)
5)返回一个对象的字符串表示形式,这个主要是给用户看:str()
1 >>> str(None)
2 'None'
3 >>> str('123')
4 '123'
5 >>> str(1234)
6 '1234'
7 >>> str()
8 ''
9 >>>
6)根据传入的参数创建一个字节数组(可变):bytearray()
1 print(bytearray('博小园','utf-8'))
2
3 ------输出结果-----
4 bytearray(b'\xe5\x8d\x9a\xe5\xb0\x8f\xe5\x9b\xad')
7)根据传入的参数创建一个不变字节数组:bytes()
1 print(bytes('博小园','utf-8'))
2
3 ------输出结果-----
4 b'\xe5\x8d\x9a\xe5\xb0\x8f\xe5\x9b\xad'
8)根据传入的参数创建一个内存查看对象:memoryview()
1 memview=memoryview(b'abcdef')
2
3 print(memview[0])
4 print(memview[-1])
5
6 --------输出结果--------
7 97
8 102
9)根据传入的参数返回对应的整数:ord()
1 print(ord('a'))
2
3 -------输出结果------
4 97
10)根据传入的参数的整数值返回对应的字符:chr()
1 print(chr(97))
2
3 -------输出结果------
4 a
11)根据传入的参数的值返回对应的二进制字符串:bin()
1 print(bin(12))
2
3 -------输出结果------
4 0b1100
12)根据传入的参数的值返回对应的八进制字符串:oct()
1 print(oct(12))
2
3 -------输出结果------
4 0o14
13)根据传入的参数的值返回对应的十六进制字符串:hex()
1 print(hex(12))
2
3 ------输出结果-----
4 0xc
14)根据传入的参数创建一个tuple元组:tuple()
1 print(tuple()) #不传递参数,创建空元组 ()
2 print(tuple('12345')) #根据可迭代参数,创建元组
3
4 ------输出结果-----
5 ()
6 ('1', '2', '3', '4', '5')
15)根据传入的参数创建一个新列表:list()
1 print(list()) #不传递参数,创建空列表 ()
2 print(list('12345')) #根据可迭代参数,创建列表
3
4 -------输出结果-------
5 []
6 ['1', '2', '3', '4', '5']
16)根据传入的参数创建一个新的字典:dict()
1 print(dict()) #不传递参数,创建一个空的字典
2
3 print(dict(x=2,y=7)) #传递键值对创建字典
4
5 print(dict((('x',1),('y',3)))) #传入可迭代对象创建新的字典
6
7 print(dict([('x',1),('y',7)]))
8 print(dict(zip(['x','y'],[2,3]))) #传入映射函数创建新的字典
9
10 ---------输出结果-----
11 {}
12 {'x': 2, 'y': 7}
13 {'x': 1, 'y': 3}
14 {'x': 1, 'y': 7}
15 {'x': 2, 'y': 3}
17)根据传入的参数创建一个新的集合:set()
1 print(set()) #传入的参数为空,返回空集合
2
3 print(set(range(7))) #传入一个可迭代对象,创建集合
4
5 -------输出结果-----
6 set()
7 {0, 1, 2, 3, 4, 5, 6}
18)根据传入的参数创建一个新的不可变集合:frozenset()
1 print(frozenset(range(8)))
2
3 -------输出结果------
4 frozenset({0, 1, 2, 3, 4, 5, 6, 7})
19)根据可迭代对象创建枚举对象:enumerate()
1 names=['zhangsan','lisi','wangwu','boxiaoyuan']
2
3 print(list(enumerate(names)))
4
5 print(list(enumerate(names,1)))
6
7 -------输出结果-----
8 [(0, 'zhangsan'), (1, 'lisi'), (2, 'wangwu'), (3, 'boxiaoyuan')]
9 [(1, 'zhangsan'), (2, 'lisi'), (3, 'wangwu'), (4, 'boxiaoyuan')]
20)根据传入的参数创建一个新的range对象:range()
1 x=range(9) #0至8
2
3 y=range(1,9) #1至8 步长为1
4
5 z=range(1,9,2) #1至8 步长为2
6
7 print(list(x))
8 print(list(y))
9 print(list(z))
10
11 -------输出结果--------
12 [0, 1, 2, 3, 4, 5, 6, 7, 8]
13 [1, 2, 3, 4, 5, 6, 7, 8]
14 [1, 3, 5, 7]
21)根据传入的参数创建一个新的可迭代对象:iter()
1 x=iter('1234')
2 print(x)
3
4 print(next(x))
5 print(next(x))
6 print(next(x))
7 print(next(x))
8 print(next(x))
9
10 -------输出结果-------
11 <str_iterator object at 0x000001BE6D71B860>
12 1
13 2
14 3
15 4
16 Traceback (most recent call last):
17 File "E:/pythontest/test06.py", line 8, in <module>
18 print(next(x))
19 StopIteration
22)根据传入的对象创建一个新的切片对象:slice()
切片函数主要对序列对象进行切去对应元素。
1 a=[0,1,2,3,4,5,6,7,8,9]
2
3 s=slice(0,9,2) #从start:0到stop:9,步长为step:2
4 print(a[s])
5
6 -------输出结果------
7 [0, 2, 4, 6, 8]
23)根据传入的参数创建一个新的子类和父类关系的代理对象:super()
1 class A:
2 def __init__(self):
3 print("A.__init__")
4
5 class B(A):
6 def __init__(self):
7 print("B.__init__")
8 super().__init__()
9
10 b=B()
11
12 -------输出结果------
13 B.__init__
14 A.__init__
24)创建一个新的object对象:object()
1 a=object()
2 a.name='boxiaoyuan' #不能设置属性,object没有该属性
3
4 --------输出结果-------
5 Traceback (most recent call last):
6 File "E:/pythontest/test06.py", line 2, in <module>
7 a.name='boxiaoyuan'
8 AttributeError: 'object' object has no attribute 'name'
3.序列操作类函数
1)判断每个可迭代对象的每个元素的值是否都是True,都是Ture,则返回True:all()
1 print(all([1,2,3,4,6])) #列表中的每个元素的值都为True,则返回True
2
3 print(all([0,2,3,4,5,6]))
4
5 print(all({})) #空字典返回True
6
7 print(all(())) #空元组返回True
8
9 ------输出结果------
10 True
11 False
12 True
13 True
2)判断可迭代对象的每个元素的值是否存在为True,存在则返回True:any()
1 print(any([1,2,3,4,6])) #列表中的存在一个为True,则返回True
2
3 print(any([0,0]))
4
5 print(any({})) #空字典返回False
6
7 print(any(())) #空元组返回False
8
9 -------输出结果------
10 True
11 False
12 False
13 False
3)使用指定方法过滤可迭代对象的元素:filter()
1 lists=[0,1,2,3,4,5,6,7,8,9]
2
3 def is_odd(x):
4 if x%2==1:
5 return x
6
7 print(list(filter(is_odd,lists)))
8
9 -------输出结果-------
10 [1, 3, 5, 7, 9]
4)使用指定方法作用传入的每个可迭代对象的元素,生成新的可迭代对象:map()
1 x=map(ord,'12345')
2
3 print(x)
4
5 print(list(x))
6
7 -------输出结果-----
8 <map object at 0x0000026B7296B860>
9 [49, 50, 51, 52, 53]
5)返回可迭代对象的下一个对象:next()
a=[0,1,2]
it=a.__iter__()
print(next(it))
print(next(it))
print(next(it))
print(next(it,3)) #传入default,当还有元素值没有迭代完,则继续迭代,如果已经迭代完,则返回默认值
-------输出结果--------
0
1
2
3
6)反转序列生成的可迭代对象:reversed()
1 a=range(10)
2 print(a) #可迭代对象
3 print(list(reversed(a)))
4
5 -------输出结果------
6 range(0, 10)
7 [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
7)对可迭代对象进行排序:sorted()
1 a=[0,2,1,9,5,7,4]
2
3 print(list(sorted(a)))
4
5 b=['a','c','d','A','C','D']
6
7 print(list(sorted(b,key=str.lower)))
8
9 -------输出结果-----
10 [0, 1, 2, 4, 5, 7, 9]
11 ['a', 'A', 'c', 'C', 'd', 'D']
8)聚合传入的每个迭代器的相同位置的元素值,然后染回元组类型迭代器:zip()
1 x=[1,2,3]
2 y=[4,5,6,7,8]
3
4 print(list(zip(x,y)))
5
6 -------输出结果------
7 [(1, 4), (2, 5), (3, 6)]
4.对象操作类函数
1)获取对象的帮助信息:help()
1 help(list)
2
3 -------输出结果------
4 Help on class list in module builtins:
5
6 class list(object)
7 | list() -> new empty list
8 | list(iterable) -> new list initialized from iterable's items
9 |
10 | Methods defined here:
11 |
12 | __add__(self, value, /)
13 | Return self+value.
14 |
15 | __contains__(self, key, /)
16 | Return key in self.
17 |
18 | __delitem__(self, key, /)
19 | Delete self[key].
20 |
21 | __eq__(self, value, /)
22 | Return self==value.
23 |
24 | __ge__(self, value, /)
25 | Return self>=value.
26 |
27 | __getattribute__(self, name, /)
28 | Return getattr(self, name).
29 |
30 | __getitem__(...)
31 | x.__getitem__(y) <==> x[y]
32 |
33 | __gt__(self, value, /)
34 | Return self>value.
35 |
36 | __iadd__(self, value, /)
37 | Implement self+=value.
38 |
39 | __imul__(self, value, /)
40 | Implement self*=value.
41 |
42 | __init__(self, /, *args, **kwargs)
43 | Initialize self. See help(type(self)) for accurate signature.
44 |
45 | __iter__(self, /)
46 | Implement iter(self).
47 |
48 | __le__(self, value, /)
49 | Return self<=value.
50 |
51 | __len__(self, /)
52 | Return len(self).
53 |
54 | __lt__(self, value, /)
55 | Return self<value.
56 |
57 | __mul__(self, value, /)
58 | Return self*value.n
59 |
60 | __ne__(self, value, /)
61 | Return self!=value.
62 |
63 | __new__(*args, **kwargs) from builtins.type
64 | Create and return a new object. See help(type) for accurate signature.
65 |
66 | __repr__(self, /)
67 | Return repr(self).
68 |
69 | __reversed__(...)
70 | L.__reversed__() -- return a reverse iterator over the list
71 |
72 | __rmul__(self, value, /)
73 | Return self*value.
74 |
75 | __setitem__(self, key, value, /)
76 | Set self[key] to value.
77 |
78 | __sizeof__(...)
79 | L.__sizeof__() -- size of L in memory, in bytes
80 |
81 | append(...)
82 | L.append(object) -> None -- append object to end
83 |
84 | clear(...)
85 | L.clear() -> None -- remove all items from L
86 |
87 | copy(...)
88 | L.copy() -> list -- a shallow copy of L
89 |
90 | count(...)
91 | L.count(value) -> integer -- return number of occurrences of value
92 |
93 | extend(...)
94 | L.extend(iterable) -> None -- extend list by appending elements from the iterable
95 |
96 | index(...)
97 | L.index(value, [start, [stop]]) -> integer -- return first index of value.
98 | Raises ValueError if the value is not present.
99 |
100 | insert(...)
101 | L.insert(index, object) -- insert object before index
102 |
103 | pop(...)
104 | L.pop([index]) -> item -- remove and return item at index (default last).
105 | Raises IndexError if list is empty or index is out of range.
106 |
107 | remove(...)
108 | L.remove(value) -> None -- remove first occurrence of value.
109 | Raises ValueError if the value is not present.
110 |
111 | reverse(...)
112 | L.reverse() -- reverse *IN PLACE*
113 |
114 | sort(...)
115 | L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
116 |
117 | ----------------------------------------------------------------------
118 | Data and other attributes defined here:
119 |
120 | __hash__ = None
2)获取对象和当前作用域的属性列表:dir()
1 import math
2
3 print(dir(math))
4
5 -----输出结果-----
6 ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
3)返回对象的唯一标识符:id()
1 name='boxiaoyuan'
2
3 print(id(name))
4
5 ------输出结果------
6 2125819230512
4)获取对象的hash码:hash()
1 name='boxiaoyuan'
2
3 print(hash(name))
4
5 -------输出结果------
6 1195266938384538974
5)根据参数返回参数的类型或者返回创建的新的对象:type()
1 print(type(1))
2 class A(object):
3 name='zhangsan'
4
5 class B(object):
6 name='lisi'
7
8 cObject=type('C',(A,B),{'name':'boxiaoyuan'}) #第一个参数是一个新的对象的名称,第二个参数是基类,第三个参数是属性
9 print(cObject.name)
10
11 -------输出结果-----
12 <class 'int'>
13 boxiaoyuan
6)查看对象的长度:len()
1 print(len('abcde'))
2
3 print(len({'a':1}))
4
5 print(len((1,2,3,4)))
6
7 ------输出结果------
8 5
9 1
10 4
7)调用对象的__repr__,获取该方法的返回值:ascii()
1 # -*- coding:utf-8 -*-
2
3
4 class Person:
5
6 def __repr__(self):
7 return "hello world"
8
9
10 if __name__ == '__main__':
11 person = Person()
12 print(ascii(person))
8)返回对象的格式化值:format()
1 #1.通过位置
2 x='a={} b={} c={}'.format('zhangsan','lisi','boxiaoyuan') #{} 不带参数
3 print(x)
4 y='a={1} b={0} c={2}'.format('zhangsan','lisi','boxiaoyuan') #{} 带参数
5 print(y)
6 #2.通过关键字参数
7 z='my English name is {name},my age is {age}'.format(name='boxiaoyuan',age='3')
8 print(z)
9 #3.通过对象属性
10 class Person:
11 def __init__(self,name,age):
12 self.name=name
13 self.age=age
14
15 p=Person('boxiaoyuan',3)
16 print('name={p.name},age={p.age}'.format(p=p))
17 #4.通过下标
18 a1=[1,2,3,4]
19 a2=['a','b','c']
20
21 print('{0[0]},{1[1]}'.format(a1,a2))
22 #5.格式化输出
23 print('左对齐定长10位 [{:<10}]'.format(13)) #对齐与填充
24 print('右对齐定长10位 [{:>10}]'.format(13))
25 print('右对齐定长10位,以0填充 [{:0>10}]'.format(13))
26
27 print('[{:.2f}]'.format(13.123456)) #小数点输出
28 print('[{:,}]'.format(12345.1234567))#以逗号分割金额
29
30 print('10转换为2进制:{:b}'.format(10)) #进制转换
31
32 -------输出结果------
33 a=zhangsan b=lisi c=boxiaoyuan
34 a=lisi b=zhangsan c=boxiaoyuan
35 my English name is boxiaoyuan,my age is 3
36 name=boxiaoyuan,age=3
37 1,b
38 左对齐定长10位 [13 ]
39 右对齐定长10位 [ 13]
40 右对齐定长10位,以0填充 [0000000013]
41 [13.12]
42 [12,345.1234567]
43 10转换为2进制:1010
9)返回当前作用域的局部变量和对象的属性列表和值:vars()
1 name='zhangsan'
2 print(vars()) #不传入参数时和locals等效,
3 print(locals())
4 class A(object):
5 name='boxiaoyaun'
6
7
8 print(vars(A))
9
10 -------输出结果------
11 {'name': 'zhangsan', '__cached__': None, '__doc__': None, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'E:/pythontest/test06.py', '__name__': '__main__', '__package__': None, '__spec__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000020E15CF6BE0>}
12 {'name': 'zhangsan', '__cached__': None, '__doc__': None, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'E:/pythontest/test06.py', '__name__': '__main__', '__package__': None, '__spec__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000020E15CF6BE0>}
13 {'name': 'boxiaoyaun', '__module__': '__main__', '__doc__': None, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>}
5.交互类函数
1)键盘输入:input()
1 password = input("请输入您的银行卡密码:")
2 print(password)
3
4 -----输出结果-----
5 请输入您的银行卡密码:123456
6 123456
2)输出到控制台:print()
%被称为格式化操作符,专门用于处理字符串中的格式。
格式化输出:
格式 | 解释 | 备注 |
%d | 整数 | %06d,表示显示如果显示的数字不够6位前面用0填充 |
%f | 浮点数 | %.2f表示小数点后只显示两位 |
%s | 字符串 | |
%% | 输出百分号 | |
1 name = "小明"
2 print("hello %s" % name)
3 age = 18
4 print("小明, 你的学号是:%06d" % 45)
5 price = 2.56
6 weight = 12
7 total = price * weight
8 print("小明,苹果的单价是%.2f,你买了%.2f斤,共%.2f元" % (price,weight,total))
9
10 --------输出结果------
11 hello 小明
12 小明, 你的学号是:000045
13 小明,苹果的单价是2.56,你买了12.00斤,共30.72元
在默认情况下,print函数输出内容之后,会自动在内容末尾增加换行,如果不希望末尾添加换行,可以在print函数输出内容的后面增加,end="",其中""中间可以指定print函数输出内容之后,继续希望显示的内容。
语法格式如下:
1 # 向控制台输出内容结束之后,不会换行
2 print("*",end="")
3
4 # 单纯的换行
5 print("")
6.编译执行类函数
1)将字符串当成有效的表达式来求值并返回计算结果:eval()
1 print(eval('1 + 1'))
在开发时不要使用eval直接转换input的结果,因为这样可以使用户任意执行操作系统命令,不安全
如__import__('os').system('ls')
2)执行动态语句块:exec()
1 # -*- coding:utf-8 -*-
2
3
4 exec('x = 3+6')
5 print(x)
3)返回对象的字符串表现形式给解释器:repr()
1 In [1]: a = 'test text'
2
3 In [2]: str(a)
4 Out[2]: 'test text'
5
6 In [3]: repr(a)
7 Out[3]: "'test text'"
8
9 In [4]:
4)将字符串编译为可以通过exec进行执行或者eval进行求值:complie()
1 # -*- coding:utf-8 -*-
2
3
4 code = 'for a in range(1, 7): print(a)'
5
6 comp = compile(code, '', 'exec') # 流程的语句使用exec
7
8 exec(comp)
9
10 code1 = '1 + 2 + 3 + 4'
11
12 comp1 = compile(code1, '', 'eval') # 求值使用eval
13
14 print(eval(comp1))
7.文件操作类函数
1)打开文件,并返回文件对象:open()
1 # -*- coding:utf-8 -*-
2
3
4 with open("d:test.txt", "r") as file:
5 for line in file:
6 print(line, end="")
8.变量操作类函数
1)获取当前作用域的全局变量和值的字典:globals()
>>> globals()
{'__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__name__': '__main__', '__spec__': None, '__builtins__': <module 'builtins' (built-in)>}
>>> a = 4
>>> globals()
{'__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__name__': '__main__', '__spec__': None, '__builtins__': <module 'builtins' (built-in)>, 'a': 4}
2)获取当前作用域的局部变量和值的字典:locals()
1 >>> def func():
2 ... print('before a')
3 ... print(locals())
4 ... a = 2
5 ... print('after a')
6 ... print(locals())
7 ...
8 >>> func()
9 before a
10 {}
11 after a
12 {'a': 2}
13 >>>
9.反射操作类函数
1)动态导入模块:__import__()
1 # -*- coding:utf-8 -*-
2
3 time = __import__("time")
4 now = time.localtime()
5 print(time.strftime("%Y-%m-%d %H:%M:%S", now))
2)判断对象是否是给定类的实例:isinstance()
1 In [1]: isinstance(1, int)
2 Out[1]: True
3
4 In [2]: isinstance('2', (int, str))
5 Out[2]: True
3)判断类是否为给定类的子类:issubclass()
1 In [1]: issubclass(bool, int)
2 Out[1]: True
3
4 In [2]: issubclass(bool, (int, str))
5 Out[2]: True
6
7 In [3]:
4)判断对象是有含有给定属性:hasattr();获取对象的属性值:getattr();设置对象的属性值:setattr();删除对象的属性值:delattr()
1 In [1]: class Person:
2 ...: def __init__(self, name):
3 ...: self.name = name
4 ...:
5
6 In [2]: p = Person('zhangsan')
7
8 In [3]: hasattr(p,'name')
9 Out[3]: True
10
11 In [4]: getattr(p, 'name')
12 Out[4]: 'zhangsan'
13
14 In [5]: setattr(p, 'name','lisi')
15
16 In [6]: getattr(p, 'name')
17 Out[6]: 'lisi'
18
19 In [7]: delattr(p, 'name')
20
21 In [8]: getattr(p, 'name')
22 ---------------------------------------------------------------------------
23 AttributeError Traceback (most recent call last)
24 <ipython-input-8-ee5bfa7ae925> in <module>
25 ----> 1 getattr(p, 'name')
26
27 AttributeError: 'Person' object has no attribute 'name'
5)检查对象是否可被调用:callable()
1 # -*- coding:utf-8 -*-
2
3
4 class Person:
5
6 def __init__(self, name):
7 self.name = name
8
9 def __call__(self, *args, **kwargs):
10 print("实例可以被调用")
11
12
13 p = Person("张三")
14 p() # 类定义了__call__,代表该类的实例可以被调用