作为一种动态语言,java与python都是支持反射机制的
#funcs.py
def func_a():
pass
def func_b():
pass
def func_c():
pass
#getattr: 动态加载模块,动态获取模块内的属性,并执行函数这样的属性
#实现func调用的动态化
import funcs
inp = input("输入想要调用的函数:")
func = getattr(funcs, f"func_{inp}")
func()
#实现了import的动态化
inp = input(‘输入你想调用的函数(模块.函数名)‘)
module, funcname = inp.split(‘.‘)
module = __import__(module)
if hasattr(module, funcname):
func = getattr(module, f"func_{inp}")
func()
else:
print("404")
#实例化 对象
#commonts.py
class person:
def __init__(self, name):
self.__name = name
def run(self, area):
print(f"{self.__name}在{area}跑步")
import commonts
import re
p = commonts.person(‘sniper‘)
p.run(‘林间小路‘)
def creatOject(name_path, *args, **kwargs):
r = re.match(r"^(.*)\.(\w+)$",name_path)
if r.group():
# print(r.groups())
module_name = r.group(1)
class_name = r.group(2)
class_obj = getattr(module, class_name)
res = class_obj(‘sniper‘)
return res
else:
print("404")
def doMethod(obj, method_name, *args, **kwargs):
if hasattr(obj, method_name):
method = getattr(obj, method_name)
method(*args, **kwargs)
else:
print(f‘{method_name}:404‘)
url - class method
原文:https://www.cnblogs.com/kangshuaibo/p/14832590.html