如何检测空物体?

How to detect empty object?

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

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 object 只有在具有 non-empty 标题时才会被认为是真实的,并且您的代码:

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

会按预期工作。

Python 对 empty 的定义(计算结果为 False)是基于通用对象,而不是您心中的任何东西。如果您控制 class(在本例中您没有),您可以添加一个 isEmpty 方法来实现您自己的想法。

但是,由于您使用的是成熟的 class,您需要通读 documentation 以了解如何 "ask" 的正确问题]你的想法"empty"。你的变量 description 肯定是 而不是 空:它在对象字段等中有你的初始化信息。默认定义是对象描述是否为 None.

我从您的使用情况推断,您可能想查看是否有未处理的消息。如果是这样,我想你可以用

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

messages 是一个双端队列,它的内在 isEmpty 方法可以做你想做的事情。