简体   繁体   English

如何从python中的另一个.py文件调用函数?

[英]How to call function from another .py file in python?

I am trying to call a function 'myfunction()' defined in another py file 'file2.py' in same directory using below code我正在尝试使用以下代码调用在同一目录中的另一个 py 文件“file2.py”中定义的函数“myfunction()”

from file2 import *

myfunction()

Unfortunately, its executing my function twice.不幸的是,它执行了我的函数两次。 The import statement is also executing the function. import 语句也在执行该函数。 Any insights on how to avoid this?关于如何避免这种情况的任何见解?

Probably you are calling inside your file2.py your function myfunction()可能你在file2.py里面调用你的函数myfunction()

when you do当你做

from file2 import *

you are loading every definitions (class, def, etc), and of course, every function called inside that .py.您正在加载每个定义(类、def 等),当然还有在 .py 中调用的每个函数。

To avoid this problem you can call your function myfunction() in your file2.py inside this scope:为避免此问题,您可以在此范围内的 file2.py 中调用函数 myfunction() :

if __name__ == '__main__':
    myfunction()

in this way it will not be executed when imported, but only if the file2.py is executed directly:这样导入时就不会执行了,只有直接执行file2.py才执行:

python3 file2.py
#File name = file2
class file3:
   def method():
      print ("printing statement")
      return "Hello world"

Main file name file1.py主文件名file1.py

from file2 import *
print(file3.method())

You can define function and write return statement to avoid extra printing您可以定义函数并编写返回语句以避免额外打印

Check your file2 and look for anything with myfunction() in it.检查您的file2并查找其中包含myfunction()任何内容。 If there is something like it, just remove it.如果有类似的东西,只需将其删除。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM