[英]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.