实现以下用例的pythonic方法是什么:

  • 有条件地导入模块
  • 从该模块继承
  • 呼叫super__init__()带有基于我们从哪个模块继承的参数

我正在努力使我的应用程序与cmdcmd2模块兼容.由于cmd2支持历史,我需要使用其他参数调用其init.但如果用户没有安装该模块,也没关系

我是这样处理的.虽然有效,但我自己不喜欢这个解决方案

try:
    import cmd2 as CMD
except:
    import cmd as CMD

class MyApp(CMD.Cmd):
    def __init__(self):
        if globals()['CMD'].__name__ == "cmd2":
            super().__init__(persistent_history_file="~/myapp_history.dat", allow_cli_args=False)
        else:
            super().__init__()

Note: This question is not specific to 100 module. That is just an example

我正在努力找到实现这一点的最佳方法

推荐答案

一种方法是基于try-except块中导入的模块创建一个中间类,在中间类中相应地重写__init__方法,以便您的主类可以干净地从中继承:

try:
    import cmd2
    class CMD(cmd2.Cmd):
        def __init__(self):
            super().__init__(persistent_history_file="~/myapp_history.dat", allow_cli_args=False)
except:
    import cmd
    class CMD(cmd.Cmd):
        def __init__(self):
            super().__init__()

class MyApp(CMD):
    # define other attributes and methods here
    pass

Python-3.x相关问答推荐

使用Python装载. iso文件

使用Polars阅读按日期键分区的最新S3镶木地板文件

按小时和日期对Pandas 数据帧进行分组

While循环不停止地等待,直到时间.睡眠结束

十进制浮点数到整型的转换错误

如何从包含SPAN文本的标记中获取链接

tkinter/python3.9 中的 Entry 子类和用户输入重复的问题

如何将函数映射到所有命名元组的元素?

将水平堆叠的数据排列成垂直

使用正则表达式提取字符串之间的文本

Dask 多阶段资源设置导致 Failed to Serialize 错误

如何在 django 中没有循环的情况下获得前键的前键?

从 Python2 到 Python3 的这种解包行为的变化是什么?

理解 Keras 的 ImageDataGenerator 类中的 `width_shift_range` 和 `height_shift_range` 参数

如何通过命令行将数组传递给python

迭代dict值

为什么`multiprocessing.Queue.get`这么慢?

创建集合的 Python 性能比较 - set() 与 {} 文字

tkinter TclError:错误的文件类型使用 askopenfilename

如何在 QGraphicsView 中启用平移和zoom