Python - reflection mechanism

Reflection is to import the module in the form of a string; in the form of a string, go to the module to find the specified function and execute it. Use the form of a string to operate (find/get/delete/add) members in an object (module), a string-based event-driven.

1. Reflection, for method invocation

library.py

def p1():
pass
def p2():
pass
def p3():
pass

user.py

import library as lib

func = input("Please input function:")

if func == "p1":
    lib.p1()
elif func == "p2":
    lib.p2()
elif func == "p3":
    lib.p3()

If there are 100 funcs, our code will be very long, so it will be convenient to use reflection

if hasattr(lib, func):  # 判断func是否在s3中有同名函数,有返还True,否则返回False
    # 不判断直接getattr时,如果“不存在”会报错
    f = getattr(lib,func)  # 获取s3中名字为func的函数,赋值给f
    f()  # 调用func同名函数

2. Reflection for module import

Ditto when each of the 100 modules has 100 members

obj = __import__("字符串")    #导入模块,不存在会报错
func = getattr(obj,"字符串1")  #获取函数
obj = __import__("路径."+"字符串",fromlist=True)    #当模块不在同一目录下时,导入模块,不加fromlist参数,只能导入"路径",注意“.”

Reflection is used a lot in web frameworks. By parsing urls, corresponding functions are executed.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326561637&siteId=291194637