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

时间:2019-07-21 05:31:02

标签: python

我有两个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:全局名称“功能”未定义
我该如何调用此函数?..是否需要超类或参数?

1 个答案:

答案 0 :(得分:1)

您需要在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"