Skip to main content
 首页 » 编程设计

python之'second_file' 没有属性 'hello' -- Discord Python Bot

2025年02月15日7zlslch

我遇到了以下问题:

第一个文件:

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() 

第二个文件:

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 中导入文件时获得的堆栈跟踪来验证这一点):

  1. 在 first_file 中导入 second_file,停止对 first_file 的解释并触发对 second_file 的完整解释。
  2. from first_file import client 停止对 second_file 的解释并触发对 first_file 的完整解释。
  3. 这一次,import second_file 被跳过(否则你会陷入无限循环)。继续解释 first_file 直到...
  4. await second_file.hello():忽略 hello() 接受两个参数的语法错误,注意解释器不知道 hello() 还没有。显然,这是一个语法错误,因为您正在使用尚未定义的内容!

要解决此问题,请使用您已经创建的架构。只需将两个 import 语句放在 second_file 的开头即可。我还冒昧地添加了您似乎忘记的 message 参数。不确定为什么您甚至需要传入 on_message 函数,但公平地说,我不知道您的用例。

第一个文件

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) 

第二个文件

async def hello(client, on_message, message): 
    await client.send_message(message.channel, "Hiii <3!")