python 动态实例化对象和调用方法的问题
在 python 中,我们通常可以通过导入模块并使用其中的类和函数来实例化对象并调用方法。但是,当我们希望动态地执行这些操作时,就需要一些技巧。
如何动态实例化对象和调用方法?
我们可以使用 importlib.import_module 动态导入模块,然后使用 getattr 函数来获取其中的类和函数。
立即学习“Python免费学习笔记(深入)”;
以下代码演示了如何实现:
# xx1.py class xxx(object): name = 'xxx' def __init__(self, name='xxx'): self.name = name def hello(self): print(f'hello {self.name}') def xxx2(name='xxx2'): print(f'hello {name}') # xx2.py import importlib class_name = 'xxx' class_func_name = 'hello' func_name = 'xxx2' xx1_module = importlib.import_module('xx1') getattr(xx1_module, class_name)().hello() getattr(getattr(xx1_module, class_name)(), class_func_name)() getattr(xx1_module, func_name)()
运行此代码将输出:
hello xxx hello xxx hello xxx2
其中,getattr(xx1_module, class_name) 获取类 xxx,getattr(xx1_module, class_name)() 实例化此类,getattr(getattr(xx1_module, class_name)(), class_func_name)() 调用其方法 hello,getattr(xx1_module, func_name)() 调用函数 xxx2。
以上就是如何动态地在 Python 中实例化对象并调用方法?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号