Python 如何检测空对象?
这是一个关于如何检测对象是否为空的通用问题。我将变量声明为对象:Python 如何检测空对象?,python,object,embed,Python,Object,Embed,这是一个关于如何检测对象是否为空的通用问题。我将变量声明为对象: 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")
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)
然而,上面的代码似乎不起作用,无论消息是否为空,我的消息都会显示出来。我该怎么办?您可以覆盖
不协调的方法。嵌入:
import discord
discord.Embed.__bool__ = lambda self: bool(self.title)
因此,Embed
对象只有在其标题非空时才会被认为是真实的,并且您的代码:
if description: client.send_message(message.channel, embed=description)
将按预期工作。Python对empty
(计算结果为False
)的定义是基于泛型对象,而不是基于您的想法。如果您控制该类(在本例中,您不控制该类),则可以添加一个isEmpty
方法来实现您自己的想法
但是,由于您使用的是一个成熟的类,因此您需要通读,以了解如何针对您的“空”概念“问”正确的问题。变量description
显然不是空的:它在对象字段等中包含初始化信息。默认定义是对象描述是否为None
我从您的使用情况推断,您可能希望查看是否有任何未完成的消息。如果是这样,我想你可以用
if description.messages:
client.send_message(message.channel, embed=description)
messages
是一个deque,其内在的isEmpty
方法可以满足您的需要。试试这个:如果!描述:client.send_message(message.channel,embed=description)discord.embed()返回什么?“Empty”对象没有很好地定义。不传递任何参数并不意味着不会使用某些默认值。@MateusMartins您确定这不是语法错误
?您可能需要设置description=None
。