如果类名在Python中动态识别,如何调用参数化构造函数
在我只有 Java 经验之前,我是 Python 新手,在 python 中,我需要调用参数构造函数,而我在运行时有许多类和类名称标识,因此我需要使用构造函数和方法创建该类对象。与静态它工作正常。对于java我可以使用class.forName(class_name)。我尝试使用 importlib, string to class 但没有成功。
示例:
class A
def _init_(self,name):
self.name = name
def some_method(self):
print('method print',self.name)
期望:想要实现 -
instance = A('instance A')
instance.some_method()
在上面的代码中,类 A 将在运行时被识别,并且我们拥有许多类似的类,并且上面的代码我需要动态实现,如何实现这一点。
I am new in Python before I have only Java experience , In python I need to invoked parameter constructor while I have many class and class name identifies on runtime so I need to create that class Object with constructor and as well method. with static it is working fine. for java I can use class.forName(class_name). I tried with importlib, string to class but did not work.
Excample:
class A
def _init_(self,name):
self.name = name
def some_method(self):
print('method print',self.name)
Expectation: want to achieve-
instance = A('instance A')
instance.some_method()
in the above code class A will be identified on Run time and similar many class we have and above code I need to implement dynamically, how can achieve this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果类在另一个文件中,请使用
getattr
如果在文件中作为类定义,请使用
globals
If classes are in another file, use
getattr
If you are in the file as the class definitions, use
globals