簡體   English   中英

如何在Python類中組織導入?

[英]How to organize imports in a Python class?

假設我有一個Python類ABC; 我想將一些非默認模塊導入到我的項目中,但是我不確定運行我的代碼的用戶是否已安裝它們。 為了進行檢查,我將導入內容封裝在try and catch塊內的類中,如下所示:

class ABC:
    _canRun = True
    try:
        import XYZ
    except Exception:
        _canRun = False


    def test_function(self):
        if self._canRun:
            import XYZ
            #do stuff using XYZ module
        else:
            print("Cannot do stuff")
            return None

我出於某種原因感覺這是不好的設計。 我可以使用更好的模式嗎?

導入通常放置在py文件的開頭:

try:
    import XYZ
except ImportError:
    XYZ = None

class ABC:
    def test_function(self):
        if XYZ is None:
            raise Exception("Cannot do stuff")

但是,當您可以選擇其他方法時,通常會執行try / except ImportError技巧:

try:
    import XYZ
except ImportError:
    import ZZTop as XYZ # if ZZTop fails, all fails. And that's fine.

class ABC:
    def test_function(self):
        XYZ.something()

否則,建議盡可能輕松地失敗:

import XYZ

class ABC:
    def test_function(self):
        XYZ.something()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM