繁体   English   中英

来自其他文件的 Python 调用函数

[英]Python calling function from other file

我有两个 python 文件文件 1 中的第一个 python 代码:

import simpleT

def funcion():
   print "Function called"
if __name__=="__main__":
  try:
     simpleT.Door().start()
     while True:
        time.sleep(1.5)
        print "Main Op"

文件 2(simpleT.py)

import threading
import time
class Door(threading.Thread):   
  def __init__ (self):
     threading.Thread.__init__(self)
  def run(self):    
     funcion()

步骤1:如果线程类在同一个文件中,我可以执行该函数
第 2 步:我想拆分它,在文件 1 上执行本地化的“函数”,该文件包含来自文件 2 上的线程的主函数,但错误说:NameError:未定义全局名称“函数”
我如何调用这个函数?..是否需要超类或参数?

你需要从 simpleT.py 中的文件 1 中导入function ,但是这样会是一个循环导入,并且会抛出错误。

所以最好的办法是为function创建一个新模块

file2.py

def funcion():
    print "Function called"

然后在simpleT.py导入这个函数

import threading
import time

from file2 import function


class Door(threading.Thread):   
    def __init__ (self):
        threading.Thread.__init__(self)
    def run(self):    
        funcion()

然后在file1.py

import simpleT


if __name__=="__main__":
    try:
        simpleT.Door().start()
        while True:
            time.sleep(1.5)
            print "Main Op"

暂无
暂无

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

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