简体   繁体   English

Python - 无法从 class 中的 py 文件调用 function?

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

I am trying to call Myfunction from a py script and this happens in a Class. But I got an error saying Myfunction is not defined.我正在尝试从 py 脚本调用Myfunction ,这发生在 Class 中。但是我收到一条错误消息,指出Myfunction未定义。 How do I avoid this?我该如何避免这种情况? I know I can put everything within file_that_contains_Myfunction_versionA(B).py into a class and call it in main() .我知道我可以将file_that_contains_Myfunction_versionA(B).py中的所有内容放入 class 并在main()中调用它。 But is there other way to do it?但是还有其他方法吗?

The trick here is that the name of the function is the same and I can't import the script at the very beginning since I don't know the condition until I run Myclass() .这里的技巧是 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()

Did you import the other script into the one you're calling it from?您是否将其他脚本导入到您调用它的脚本中?

from otherscript import function_A

function_A()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 python:类中的函数调用 - python: function call from within a class Python 从不同的.py 文件中调用导入的 function,但导入的 function 在主文件中看不到其他导入的模块 - Python call a imported function from a different .py file, but the imported function cannot see the other imported moduel in main file 如何从另一个py文件调用函数到django中的模型类 - How to call a function from another py file to a model class in django 为什么python不能从python函数内部调用Javascript()? - Why cannot python call Javascript() from within a python function? 如何从 python (py) 文件调用 C++ 函数? - How to call a C++ function from a python (py) file? 来自另一个py文件的maya python调用函数 - maya python call function from another py file 如何从python中的另一个.py文件调用函数? - How to call function from another .py file in python? 在不使用类的情况下从 Python 中的另一个函数中调用函数 - Call a function from within another function in Python without using class 使用 Python 修补来自不同文件的函数内的函数调用 - Patch a function call within function from different file using Python 执行.py文件,在for循环中调用python function - execute .py file, call python function in for loop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM