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
31
32
33
34
35
36
37
38
39
40
41
42
| class Demo(object):
def __init__(self,name):
self.name = name
def method(self):
print("i am method")
d = Demo('luenci')
# 如果d 对象中有属性name则打印self.name的值,否则打印not find
print(getattr(d,'name','not find'))
print(getattr(d,'age','not find'))
#如果有方法method,否则打印其地址,否则打印not find
print(getattr(d, 'method', 'not find'))
print(getattr(d, 'methods', 'not find'))
#如果有方法method,运行函数并打印None否则打印not find
print(getattr(d, 'method', 'not find')())
# 说明:判断对象object是否包含名为name的特性(hasattr是通过调用getattr(ojbect, name)是否抛出异常来实现的)
print(hasattr(d, 'name'))
# 增加和修改参数
# d.age = 18
setattr(d,'age', 18)
setattr(d,'name','jack')
print(d.__dict__)
# 删除 属性 不能删除属性对应的值, 但是可以使用setattr来修改
delattr(d,'age')
print(d.__dict__)
out:
luenci
not find
<bound method Demo.method of <__main__.Demo object at 0x000001710E9359B0>>
not find
i am method
None
True
{'name': 'jack', 'age': 18}
{'name': 'jack'}
|