本文实例讲述了Python3.6简单反射操作。分享给大家供大家参考,具体如下:
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
# -*- coding:utf-8 -*- #!python3 # ----------------------- # __Author : tyran # __Date : 17-11-13 # ----------------------- class Base: def __init__( self ): self .name = 'aaa' self .age = 18 def show( self ): print ( self .age) # 通过getattr()找到对象的成员 base = Base() v = getattr (base, 'name' ) print (v) # aaa func1 = getattr (base, 'show' ) func1() # 18 # 通过hasattr()查找成员是否存在 print ( hasattr (base, 'name' )) # True print ( hasattr (base, 'name1' )) # False # 通过setattr()给对象添加成员 setattr (base, 'k1' , 'v1' ) print (base.k1) delattr (base, 'k1' ) # v1 # print(base.k1) 报错AttributeError: 'Base' object has no attribute 'k1' # ------------------------------------------------------------------------- # Class也是一个对象 class ClassBase: sex = 'male' def __init__( self ): self .name = 'aaa' self .age = 11 @staticmethod def show(): print ( 'I am static' ) @classmethod def c_method( cls ): print ( cls .sex) sex_value = getattr (ClassBase, 'sex' ) print (sex_value) s_func = getattr (ClassBase, 'show' ) s_func() c_func = getattr (ClassBase, 'c_method' ) c_func() # 这些都没问题 setattr (ClassBase, 'has_girlfriend' , True ) # 添加静态成员 print (ClassBase.has_girlfriend) # True # ---------------同理,模块也是对象------------- # 我新建了一个模块s1.py,我把内容复制下来 # class S1: # def __init__(self): # self.name = 'aaa' # self.age = 22 # # def show(self): # print(self.name) # print(self.age) # # # def func1(): # print('page1') # # # def func2(): # print('page2') # 一个类,两函数 import s1 s1_class = getattr (s1, 'S1' , None ) if s1_class is not None : c1 = s1_class() c1.show() # aaa # 22 getattr (s1, 'func1' )() # page1 f2 = 'func2' if hasattr (s1, f2): getattr (s1, 'func2' )() # page2 |
注释中说明的s1.py如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
# -*- coding:utf-8 -*- #!python3 class S1: def __init__( self ): self .name = 'aaa' self .age = 22 def show( self ): print ( self .name) print ( self .age) def func1(): print ( 'page1' ) def func2(): print ( 'page2' ) # 一个类,两函数 |
程序运行结果:
希望本文所述对大家Python程序设计有所帮助。
原文链接:https://blog.csdn.net/tyrantu1989/article/details/78530180