【问题标题】:How to detect empty object?如何检测空物体?
【发布时间】:2019-07-08 20:35:54
【问题描述】:

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

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)

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

【问题讨论】:

  • 试试这个:if !description: client.send_message(message.channel, embed=description)
  • discord.Embed() 返回什么?
  • “空”对象定义不明确。仅仅因为你没有传递任何参数并不意味着没有一些默认值可以被使用。
  • @MateusMartins 你确定这不是syntax error 吗?
  • 您可能想要设置description = None

标签: python object embed


【解决方案1】:

你可以覆盖discord.Embed__bool__方法:

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

这样Embed 对象只有在标题非空时才会被认为是真实的,并且您的代码:

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

会按预期工作。

【讨论】:

    【解决方案2】:

    Python 对empty 的定义(评估为False)是基于通用对象,而不是基于你的想法。如果你控制了这个类(在这种情况下你没有控制),你可以添加一个isEmpty 方法来实现你自己的想法。

    但是,由于您使用的是成熟的课程,因此您需要通读documentation 以了解如何为您的“空”概念“提出”正确的问题。您的变量description 绝对为空:它在对象字段等中有您的初始化信息。默认定义是对象描述是否为None

    我从您的使用情况推断,您可能想查看是否有任何未完成的消息。如果是这样,我认为您可以这样做

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

    messages 是一个双端队列,其固有的 isEmpty 方法可以满足您的需求。

    【讨论】:

      猜你喜欢
      • 2015-01-26
      • 2013-12-15
      • 2011-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-20
      • 2018-11-18
      相关资源
      最近更新 更多