实现以下用例的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请求从特定URL下载图像时出错

给定panda代码的分组和百分比分布pyspark等价

如何定义部署用 Python 编写的 Firestore 第二代函数的区域/位置?

对大型数据框中的选定列进行重新排序

重复数组直到一定长度 groupby pandas

DataFrame列中如何迭代重复值?

如何提高 snowpark 程序的性能?

在 groupby 之后,Pandas 在特定类别中获得最常见和最后的值

如果集合大于 len(x),则 pandas 在重复的行中拆分集合列

如何在两个矩阵的比较中允许任何列的符号差异,Python3?

为什么 numpy 的 `np.char.encode` 会将一个空的 unicode 数组变成一个空的 `float64` 数组?

如何在python 3.10中将列表项(字符串类型)转换为模块函数

合并两个numpy数组

如何模拟 Django 模型对象(及其方法)?

tensorflow 中 numpy.newaxis 的替代方案是什么?

try 注释散列变量时,ABCMeta对象不可下标

cv2 python 没有 imread 成员

在python中,如果一个函数没有return语句,它会返回什么?

异常被忽略是什么类型的消息?

如何使用 Celery 和 Django 将任务路由到不同的队列