Python从其他fi调用函数

2024-09-30 00:34:45 发布

您现在位置: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(简单.py)你知道吗

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

第一步: 如果线程的类在同一个文件中,我可以执行该函数
第二步: 我想拆分它,在文件1上执行localed“function”,它包含来自文件2上线程的主函数,但错误是: 名称错误:未定义全局名称“函数”
如何调用此函数?。。是否需要超类或参数?你知道吗


Tags: 文件函数importself名称timeinitdef
1条回答
网友
1楼 · 发布于 2024-09-30 00:34:45

您需要从中的文件1导入function简单.py但这样,它将是一个循环导入,并将抛出一个错误。你知道吗

所以最好是为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"

相关问题 更多 >

    热门问题