
python 动态实例化对象和调用方法的问题
在 python 中,我们通常可以通过导入模块并使用其中的类和函数来实例化对象并调用方法。但是,当我们希望动态地执行这些操作时,就需要一些技巧。
如何动态实例化对象和调用方法?
我们可以使用 importlib.import_module 动态导入模块,然后使用 getattr 函数来获取其中的类和函数。
立即学习“Python免费学习笔记(深入)”;
以下代码演示了如何实现:
# xx1.pyclass 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.pyimport importlibclass_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 xxxhello xxxhello 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 中实例化对象并调用方法?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1353022.html
微信扫一扫
支付宝扫一扫