Python,以正确的方式进行条件导入 [英] Python, doing conditional imports the right way

查看:55
本文介绍了Python,以正确的方式进行条件导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我有一个叫A的班级.

Right now I have a class called A.

我有一些这样的代码.

from my.package.location.A import A

...


foo = A.doSomething(bar)

太好了.

但是现在我有了一个称为A的新版本A,但使用的是另一个软件包,但是我只想在特定情况下使用另一个A.所以我可以做这样的事情:

But now I have a new version of A called A, but in a different package, but I only want to use this other A in a certain scenario. So I can do something like this:

if(OldVersion):
    from my.package.location.A import A
else:
    from new.package.location.A import A

...

foo = A.doSomething(bar)

这很好.但这是丑陋的.我该如何做得更好?我真的很想做这样的事情

This works fine. But it is ugly. How can I do this better? I really want to do something like this

from my.abstraction.layer.AFactory import AFactory
...
myA = AFactory.giveMeA() # this looks at "OldVersion" and gives me the correct A
foo = myA.doSomething(bar)

有没有一种方法可以使我更轻松?没有工厂层?现在,这可以将类上的每个静态方法调用分成两行.我总是可以在一个类中保留一个引用以减少影响,但是我真的希望python有一个更简单的解决方案.

is there a way I can do that easier? Without the factory layer? This now can turn every static method call on my class into 2 lines. I can always hold a reference in a class to reduce the impact, but im really hoping python has a simpler solution.

推荐答案

将行放入a_finder.py:

Put your lines into a_finder.py:

if OldVersion:
    from my.package.location.A import A
else:
    from new.package.location.A import A

然后在您的产品代码中:

Then in your product code:

from a_finder import A

您将获得适当的A.

这篇关于Python,以正确的方式进行条件导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆