gpt4 book ai didi

python - 如何检测空物体?

转载 作者:行者123 更新时间:2023-12-01 08:20:11 25 4
gpt4 key购买 nike

这是一个关于如何检测对象是否为空的通用问题。我将变量声明为对象:

description = discord.Embed()

将其通过可能会或可能不会将参数传递给对象的方法,即:

def my_function(x, y, z):
...some code goes here...
if x == "some variable":
description = discord.Embed(title="X", desc="Y + z")
return description
else:
description = discord.Embed()
return description

我希望仅在描述不为空时才显示描述:

if description: client.send_message(message.channel, embed=description)

但是上面的代码似乎不起作用,无论我的消息是否为空,它都会显示。我该怎么办?

最佳答案

您可以覆盖 discord.Embed__bool__ 方法:

import discord
discord.Embed.__bool__ = lambda self: bool(self.title)

这样,只有当 Embed 对象具有非空标题时,该对象才会被视为真实,并且您的代码:

if description: client.send_message(message.channel, embed=description)

将按预期工作。

关于python - 如何检测空物体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54696813/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com