[英]How to call function from another .py file in python?
我正在尝试使用以下代码调用在同一目录中的另一个 py 文件“file2.py”中定义的函数“myfunction()”
from file2 import *
myfunction()
不幸的是,它执行了我的函数两次。 import 语句也在执行该函数。 关于如何避免这种情况的任何见解?
可能你在file2.py
里面调用你的函数myfunction()
当你做
from file2 import *
您正在加载每个定义(类、def 等),当然还有在 .py 中调用的每个函数。
为避免此问题,您可以在此范围内的 file2.py 中调用函数 myfunction() :
if __name__ == '__main__':
myfunction()
这样导入时就不会执行了,只有直接执行file2.py才执行:
python3 file2.py
#File name = file2
class file3:
def method():
print ("printing statement")
return "Hello world"
主文件名file1.py
from file2 import *
print(file3.method())
您可以定义函数并编写返回语句以避免额外打印
检查您的file2
并查找其中包含myfunction()
任何内容。 如果有类似的东西,只需将其删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.