如何在 Python 中根据运行时的输入实例化类(实现)

发布于 2025-01-19 11:49:51 字数 524 浏览 3 评论 0原文

我的程序需要根据用户输入选择一个类。

这些类具有具有不同实现的相同方法(从同一ABC继承)。而且可能有30多个课程。

# myABC.py
class myABC(ABC):
  @abstractmethod
  def foo():
    pass

# A.py
class A(myABC.myABC):
 def foo():
  print("A")

# B.py
class B(myABC.myABC):
 def foo():
  print("B")

我只有一种方法是使用If-Else。但这显然不是一个超过30的好选择,如果Elif语句

# main.py

def get_obj(usr_input: str):
  if usr_input == "A":
    return A.A()
  elif usr_input == "B":
    return B.B()
  ...

还有其他方法可以解决此问题吗?多谢。

My program needs to select a class based on user input.

The classes have the same set of methods (inherited from the same ABC) with different implementations. And there are probably more than 30 classes.

# myABC.py
class myABC(ABC):
  @abstractmethod
  def foo():
    pass

# A.py
class A(myABC.myABC):
 def foo():
  print("A")

# B.py
class B(myABC.myABC):
 def foo():
  print("B")

I have only one way in my mind is using if-else. But that is obviously not a great option with more than 30 if, elif statements

# main.py

def get_obj(usr_input: str):
  if usr_input == "A":
    return A.A()
  elif usr_input == "B":
    return B.B()
  ...

Are there any other ways that can solve this problem? Thanks a lot.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

楠木可依 2025-01-26 11:49:52

也许动态导入可以帮助你。

#importlib.import_module

您应该确保您的文件名和类姓名。

然后你可以

import importlib

def get_obj(usr_input: str):
    mod = importlib.import_module(usr_input)
    usr_class = getattr(mod, usr_input)
    return usr_class() 

在上面假设你的子类的文件名和类名与usr_input相同

Maybe dynamic import can help you.

#importlib.import_module

You should ensure your file name and class name.

Then you can

import importlib

def get_obj(usr_input: str):
    mod = importlib.import_module(usr_input)
    usr_class = getattr(mod, usr_input)
    return usr_class() 

Above assump that your subclass's file name and class name are same as usr_input

拥抱没勇气 2025-01-26 11:49:52

如果您想从主脚本中删除逻辑,您可以创建一个包含实例化所有逻辑的工厂类。

这样,实例化的逻辑将与主逻辑解耦。

另外,如果您使用的是 python 3.10 或更高版本,您应该使用 match 语句而不是多个 if else

If you want to remove the logic from the main script, you could just create a Factory class that contains all the logic for the instantiation.

This way the logic for the instantiation would be decoupled from the main logic.

Also, if you are using python 3.10 or higher, you should use a match statement instead of multiple if else

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