Python反射

day25

反射

通过字符串的形式操作对象中的成员

 1 class Foo:
 2     def __init__(self, name, age):
 3         self.name = name
 4         self.age = age
 5 
 6     def show(self):
 7         return "%s-%s" %(self.name, self.age)
 8 
 9 obj = Foo('alex', 18)
10 obj.name = 'nizhipeng'
11 
12 b = 'name'
13 
14 print(obj.__dict__)#字典
15 print(obj.__dict__[b])
16 
17 #去什么东西里获取内容
18 #以字符串形式取内容
19 v = getattr(obj, 'age')      #name或age
20 print(v)
21 
22 func = getattr(obj, 'show') #取对象中的方法
23 print(func)
24 r = func()  #执行对象中的方法
25 print(r)
26 
27 
28 print(hasattr(obj, 'name'))   #检测有无name成员
29 
30 setattr(obj, 'k1', 'v1')
31 print(obj.k1)
32 
33 # delattr(obj, 'k1')
34 # print(obj.k1)

getattrhasattrsetattrdelattr

可以通过字符串操作对象中的成员和方法。

执行结果:

{'name': 'nizhipeng', 'age': 18}
nizhipeng
18
<bound method Foo.show of <__main__.Foo object at 0x7f10935e1d30>>
nizhipeng-18
True
v1

Process finished with exit code 0

模块级别的反射

s2.py

1 name = 'alex'
2 def func():
3     return 'func'
4 
5 class Foo:
6     def __init__(self):
7         self.name = 123

s1.py

 1 import s2#模块中
 2 r1 = s2.name
 3 print(r1)
 4 r2 = s2.func()
 5 print(r2)
 6 
 7 print("反射在模块中的使用:")#取成员
 8 r1 = getattr(s2, 'name')#模块也是对象
 9 print(r1)
10 
11 r2 = getattr(s2, 'func')#取函数
12 result = r2()
13 print(result)
14 
15 cls = getattr(s2, 'Foo')#取类
16 print(cls)
17 obj = cls()#对象
18 print(obj)

s2.py调用s1.py,调用s1.py中的成员、类和函数。

执行结果:

alex
func
反射在模块中的使用:
alex
func
<class 's2.Foo'>
<s2.Foo object at 0x7f0cb05b47b8>

Process finished with exit code 0

反射的应用实例:

s2.py

1 def f1():
2     return '首页'
3 
4 def f2():
5     return '新闻'
6 
7 def f3():
8     return '精华'

s1.py

 1 import s2
 2 
 3 inp = input('请输入要查看的URL:')
 4 # 比较繁琐
 5 # if inp == 'f1':
 6 #     s2.f1()
 7 # elif inp == 'f2':
 8 #     s2.f2()
 9 #
10 if hasattr(s2, inp):
11     func = getattr(s2, inp)
12     result = func()
13     print(result)
14 
15 else:
16     print('404')

直接根据输入调用模块中的函数。

执行结果:

请输入要查看的URL:f3
精华

Process finished with exit code 0
原文地址:https://www.cnblogs.com/112358nizhipeng/p/9861101.html