【问题标题】:share functions between two files在两个文件之间共享函数
【发布时间】:2020-02-29 01:12:12
【问题描述】:

我正在创建一个测验程序,其中有一个用户输入答案的前端文件和一个后端问题存储文件。我想在两个文件之间共享每个文件中定义的函数,但是我似乎只能从一个文件到另一个文件共享函数,而不是从两个文件相互共享函数

我尝试在 file1 中执行:从 file2 导入 function2,然后在 file2 中执行:从 file1 导入 function1。但是,这不起作用。我只是得到一个无法导入 function1 的错误。

#file1 (backend)
from physicstester_frontend import answer

def quantum_test():

    while True:
        qq1 = "describe the experiments that lead to wave particle duality."
        print(qq1)
        answer()
        qq1_words = ["double slit", "diffraction", "interference", "wave", "photoelectric", "effect", "photon"]
        if all(word in ans for word in qq1_words):
            print("correct") #prints correct if all required words are in string
            break  
        else:
            print("not a full description, try again")
            continue

#file2 (frontend)
from physicstester_data import quantum_test

print("physics tester")
print("topics: \nQuantum\n..\n..\n..")
topics = input("which topic would you like to be tested on?: ")

if topics.lower() == "quantum":
    quantum_test()

def answer():
    global ans
    ans = input("answer: ")

当我这样做时,我得到了

ImportError: cannot import name 'quantum_test' from 'physicstester_data'

【问题讨论】:

  • 请分享目录结构和file1和file2文件名
  • 在询问产生异常的代码时,请始终在问题中包含完整的 Traceback。复制 Traceback 并将其粘贴到问题中,然后将其格式化为代码(选择它并键入 ctrl-k)
  • 能否创建第三个文件,在其中放置服务器文件和客户端文件共享的所有功能?
  • 文件名是physicstester_data.pyphysicstester_frontend.py?
  • 是的,这些是文件名

标签: python python-3.x


【解决方案1】:

import 循环不好。

def answer() 放入自己的文件answer.py 以打破循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-24
    • 1970-01-01
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 2019-10-08
    • 2021-07-16
    相关资源
    最近更新 更多