簡體   English   中英

Python - 無法從 class 中的 py 文件調用 function?

[英]Python - Cannot call a function from a py file within a class?

我正在嘗試從 py 腳本調用Myfunction ,這發生在 Class 中。但是我收到一條錯誤消息,指出Myfunction未定義。 我該如何避免這種情況? 我知道我可以將file_that_contains_Myfunction_versionA(B).py中的所有內容放入 class 並在main()中調用它。 但是還有其他方法嗎?

這里的技巧是 function 的名稱是相同的,我無法在一開始就導入腳本,因為在運行Myclass()之前我不知道條件。

class Myclass():
    def __init__(self):
        self.main()

    def main(self):
            if conditionA:
                exec(open("./file_that_contains_Myfunction_versionA.py").read())
                Myfunction()
            if conditionB:
                exec(open("./file_that_contains_Myfunction_versionB.py").read())
                Myfunction()

您是否將其他腳本導入到您調用它的腳本中?

from otherscript import function_A

function_A()

暫無
暫無

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

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