如果类名在Python中动态识别,如何调用参数化构造函数

发布于 2025-01-17 04:09:52 字数 493 浏览 1 评论 0原文

在我只有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

揽清风入怀 2025-01-24 04:09:52

如果类在另一个文件中,请使用 getattr

import module_with_my_classes

x = getattr(module_with_my_classes, 'A')

如果在文件中作为类定义,请使用 globals

x = globals()['A']
# x is a A instance

If classes are in another file, use getattr

import module_with_my_classes

x = getattr(module_with_my_classes, 'A')

If you are in the file as the class definitions, use globals

x = globals()['A']
# x is a A instance
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文