python中hasattr getattr setattr用法
1 >>> class test():
2 ... name="xiaohua"
3 ... def run(self):
4 ... return "HelloWord"
5 ...
6 >>> t=test()
7 >>> getattr(t, "name") #获取name属性,存在就打印出来。
8 'xiaohua'
9 >>> getattr(t, "run")#获取run方法,存在就打印出方法的内存地址。
10 <bound method test.run of <__main__.test instance at 0x0269C878>>
11 >>> getattr(t, "run")()#获取run方法,后面加括号可以将这个方法运行。
12 'HelloWord'13 >>> getattr(t, "age")#获取一个不存在的属性。
14 Traceback (most recent call last):
15 File "<stdin>", line 1, in <module>
16 AttributeError: test instance has no attribute 'age'
17 >>> getattr(t, "age","18")#若属性不存在,返回一个默认值。
18 '18'
19 >>>
页:
[1]