'second_file' 没有属性 'hello' -- Discord Python Bot
'second_file' has no attribute 'hello' -- Discord Python Bot
我运行遇到以下问题:
First_File:
import discord
import second_file
client = discord.Client()
[...]
@client.event
async def on_message(message):
if message.content.lower().startswith("!hi"):
await second_file.hello()
Second_File:
from first_file import client
from first_file import on_message
async def hello(client, on_message):
await client.send_message(message.channel, "Hiii <3!")
现在我收到错误消息:module 'second_file' has no attribute 'hello'
。
为什么它不调用函数?
与实际发生的情况相比,这是一条相当神秘的错误消息。您试图同时从两个文件导入,这会导致问题。无论何时导入,都会解释完整的文件,即使您使用的是 from file import thing
。更具体地说,await second_file.hello()
失败是因为 second_file
在您访问时尚未完全导入。
这是正在执行的内容及其失败的原因(您可以从尝试在 python3 REPL 中导入文件时获得的堆栈跟踪来验证这一点):
import second_file
in first_file, 停止对 first_file 的解释并触发对 second_file. 的完整解释
from first_file import client
停止对 second_file 的解释并触发对 first_file. 的完整解释
- 这一次,
import second_file
被跳过(否则你会陷入无限循环)。继续解释 first_file 直到...
await second_file.hello()
:忽略 hello()
接受两个参数的语法错误,注意解释器还不知道 hello()
。显然,这是一个语法错误,因为您正在使用尚未定义的内容!
要解决此问题,请使用您已经创建的架构。只需删除 second_file 开头的两个 import 语句。我还冒昧地添加了您似乎忘记的 message
参数。不确定为什么你甚至需要传入 on_message
函数,但公平地说,我不知道你的用例。
first_file
import discord
import second_file
client = discord.Client()
[...]
@client.event
async def on_message(message):
if message.content.lower().startswith("!hi"):
await second_file.hello(client, on_message, message)
second_file
async def hello(client, on_message, message):
await client.send_message(message.channel, "Hiii <3!")
我运行遇到以下问题:
First_File:
import discord
import second_file
client = discord.Client()
[...]
@client.event
async def on_message(message):
if message.content.lower().startswith("!hi"):
await second_file.hello()
Second_File:
from first_file import client
from first_file import on_message
async def hello(client, on_message):
await client.send_message(message.channel, "Hiii <3!")
现在我收到错误消息:module 'second_file' has no attribute 'hello'
。
为什么它不调用函数?
与实际发生的情况相比,这是一条相当神秘的错误消息。您试图同时从两个文件导入,这会导致问题。无论何时导入,都会解释完整的文件,即使您使用的是 from file import thing
。更具体地说,await second_file.hello()
失败是因为 second_file
在您访问时尚未完全导入。
这是正在执行的内容及其失败的原因(您可以从尝试在 python3 REPL 中导入文件时获得的堆栈跟踪来验证这一点):
import second_file
in first_file, 停止对 first_file 的解释并触发对 second_file. 的完整解释
from first_file import client
停止对 second_file 的解释并触发对 first_file. 的完整解释
- 这一次,
import second_file
被跳过(否则你会陷入无限循环)。继续解释 first_file 直到... await second_file.hello()
:忽略hello()
接受两个参数的语法错误,注意解释器还不知道hello()
。显然,这是一个语法错误,因为您正在使用尚未定义的内容!
要解决此问题,请使用您已经创建的架构。只需删除 second_file 开头的两个 import 语句。我还冒昧地添加了您似乎忘记的 message
参数。不确定为什么你甚至需要传入 on_message
函数,但公平地说,我不知道你的用例。
first_file
import discord
import second_file
client = discord.Client()
[...]
@client.event
async def on_message(message):
if message.content.lower().startswith("!hi"):
await second_file.hello(client, on_message, message)
second_file
async def hello(client, on_message, message):
await client.send_message(message.channel, "Hiii <3!")