【问题标题】:How to create separate files for functions, then import them?如何为函数创建单独的文件,然后导入它们?
【发布时间】:2021-01-26 12:53:15
【问题描述】:

我有这个工作代码:

from telegram import Update
from telegram.ext import Updater, CommandHandler, CallbackContext

updater = Updater('token')

def hello(update: Update, context: CallbackContext) -> None:
    update.message.reply_text('Hello!')

updater.dispatcher.add_handler(CommandHandler('hello', hello))

updater.start_polling()
updater.idle()

我希望每个函数都有一个单独的文件,并有一个 main.py 我在其中导入它们。

所以我开始用这个创建一个 f1.py

def hello(update: Update, context: CallbackContext) -> None:
    update.message.reply_text('Hello!')

然后用

将它导入到一个main.py
from f1 import hello
hello()

显然,这是行不通的(缺少参数)。如何正确操作?

【问题讨论】:

  • 您能告诉我们您的文件是如何构成的吗?

标签: python function file import python-telegram-bot


【解决方案1】:

您的main.pyf1.py 很好,但是在您的main.py 中的updater.dispatcher 上缺少某些东西。试试这个:

from telegram import Update
from telegram.ext import Updater, CommandHandler, CallbackContext

#On my bots I prefer to import the entire module than a function from a module,
#because I usually have users.py (all functions for users), clients.py (all 
#functions for clients), devs.py (all functions for developer's team) and so on
import f1

updater = Updater('token')

#Calling a function from a module must have a callback, as shown bellow
updater.dispatcher.add_handler(CommandHandler('hello', callback = f1.hello))

updater.start_polling()
updater.idle()

试试这个,让我知道它是否适合你!

【讨论】:

  • 很高兴能帮上忙!!
【解决方案2】:

有关更多信息,这里是导入自己的模块的好来源:

https://docs.python.org/3/tutorial/modules.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-02
    • 2021-05-12
    • 2013-12-28
    • 2023-03-30
    相关资源
    最近更新 更多