如何在 Python 中根据运行时的输入实例化类(实现)
我的程序需要根据用户输入选择一个类。
这些类具有具有不同实现的相同方法(从同一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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许动态导入可以帮助你。
#importlib.import_module
您应该确保您的文件名和类姓名。
然后你可以
在上面假设你的子类的文件名和类名与
usr_input
相同Maybe dynamic import can help you.
#importlib.import_module
You should ensure your file name and class name.
Then you can
Above assump that your subclass's file name and class name are same as
usr_input
如果您想从主脚本中删除逻辑,您可以创建一个包含实例化所有逻辑的工厂类。
这样,实例化的逻辑将与主逻辑解耦。
另外,如果您使用的是 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