如果在赋值i时向集合添加变量,Python为什么会赋值None

2024-04-18 20:03:11 发布

您现在位置:Python中文网/ 问答频道 /正文

而不是将变量添加到正确的集合中,例如:

 set_to_add_to = set()
 set_to_add_to.add("test")

我只是不小心编码了:

 set_to_add_to = set()
 set_to_add_to = set_to_add_to.add("test")

虽然我知道这不是向集合中添加项的方式,但我认为这样做会导致set_to_add_to取值None,这一点让我大吃一惊。我不明白为什么会发生这种情况-它似乎类似于int_variable = int_variable + 5,这是正确的。你知道吗

类似地:

 set_to_add_to = set()
 new_set = set_to_add_to.add("test")

结果new_set取值None为什么不是先将test添加到set_to_add_to然后再分配给new_set?你知道吗


Tags: totestnoneadd编码new方式情况
2条回答

首先,要注意所有函数(包括用户定义的和内置的函数)都会返回一些东西。通常,通过return语句很容易看到函数返回的内容。在没有return语句的函数中,默认情况下返回None。你知道吗

现在,我们来看看为什么一些python常用函数返回None。你知道吗

一般来说,就地修改对象的python函数返回None。你知道吗

例如:

x = [4,3,7,8,2]
y = sorted(x) #y is now a sorted list because sorted returns a copy!
y = x.sort() # y is now None because x was sorted in place

一个值得注意的例外是pop()函数,它返回被弹出的值。你知道吗

请查看此帖子以获得更详细的解释:

Is making in-place operations return the object a bad idea?

x = [4,3,7,8,2]
val = x.pop() 

#val = 2
#x = [4,3,7,8]

集合的.add()方法总是返回None,就像.append()list方法返回None一样。你知道吗

相关问题 更多 >