【问题标题】:How do i run an import from a function? [duplicate]如何从函数运行导入? [复制]
【发布时间】:2021-12-26 03:47:47
【问题描述】:

我需要帮助了解如何从函数运行我的导入代码!

  sayTime(timespeech)
import time
list = ["whats the time","what's the time","WHAT'S THE TIME?","Whats the time","Whats the time?","What's the time?","WHATS THE TIME?","what's the time?","WHATS THE TIME"]
list2 = ["hi","Hi","Hello","hello","Hey","hey"]
while True:
    answer = input("How can i help: ")

    if answer in list:
      timespeech.sayTime()
    
    if answer in list2:
        time.sleep(0.5)
        print("Hi Max!") 
        time.sleep(2)

如您所见,我是 python 新手。 time speech 是另一个 .py 文件,当我执行 import timespeech 时会运行它。我试图通过一个函数运行它,它声明if answer in list: timespeech.sayTime() 我相信你应该将它作为def sayTime(timespeech): 但我不确定之后会发生什么。请帮忙!

【问题讨论】:

  • 如果您不确定如何定义函数,我强烈建议您学习一些好的 Python 教程,这对您有很大帮助。
  • 试试from timespeech import sayTime
  • 您不想“从函数运行导入代码”。您希望 1) 在开始时导入模块,2) 以在导入时不会发生任何重要事情的方式编写模块(请参阅链接的副本),以及 3) 显式从该模块调用 某个函数(或创建一个类的实例,并调用一个方法)。如果其中任何一个不清楚,您可能应该先遵循教程。例如,尝试将python how to use modules 放入搜索引擎。
  • “我相信你应该把它写成def sayTime(timespeech):,但我不确定之后会发生什么。”然后是你写@987654328的地方应该发生的事情@。但是不,应该只是def sayTime():

标签: python


【解决方案1】:

如果你想导入在另一个.py文件(名为timespeech.py)中定义的函数(名为sayTime),你必须通过以下方式导入函数:

from timespeech import sayTime

然后编写其余的代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    • 2013-05-05
    • 1970-01-01
    • 2012-08-13
    • 2021-12-31
    • 2019-12-22
    相关资源
    最近更新 更多