首页 > 解决方案 > Python - 无法从类中的 py 文件调用函数?

问题描述

我试图Myfunction从 py 脚本调用,这发生在一个类中。但我收到一个错误,说Myfunction未定义。我该如何避免这种情况?我知道我可以将所有内容file_that_contains_Myfunction_versionA(B).py放入一个类中并调用它main()。但是还有其他方法吗?

这里的诀窍是函数的名称是相同的,我不能在一开始就导入脚本,因为我不知道条件,直到我运行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()

标签: pythonfunctionclassexec

解决方案


您是否将另一个脚本导入到您从中调用它的脚本中?

from otherscript import function_A

function_A()

推荐阅读