使用基于条件的Python模块

2024-06-08 18:06:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我想根据某些条件在类中动态导入模块。你知道吗

    class Test(object):
        def __init__ (self,condition):
            if condition:
                import module1 as mymodule
            else:
                import module2 as mymodule

            self.mymodule = mymodule

        def doTest(self):
            self.mymodule.doMyTest

其中模块1和模块2以不同的方式实现doMyTest。你知道吗

称之为

    mytest1 = Test(true)  # Use module1
    mytest2.doTest()

    mytest2 = Test(false)  # Use module2
    mytest2.doTest()

这很管用,但有没有更惯用的方法呢?有什么可能的问题吗?你知道吗


Tags: 模块testimportselfusedefascondition
1条回答
网友
1楼 · 发布于 2024-06-08 18:06:10

当然,通常您不希望在__init__方法的中间导入模块,但是测试类显然是该规则的例外,所以让我们忽略这一部分,并假设您在顶层执行此操作:

if test_c_implementation:
    import c_mymodule as mymodule
else:
    import py_mymodule as mymodule

这很地道。事实上,在stdlib和其他由核心开发人员编写的代码中可以看到这样的代码。你知道吗

除了在非常常见的EAFP情况下,条件只是为了避免异常,在这种情况下,这样做更为惯用:

try:
    import lxml.etree as ET
except ImportError:
    import xml.etree.cElementTree as ET

相关问题 更多 >