简体   繁体   English

使用Python中的方法时,何时重新声明变量?

[英]When to redeclare a variable when using a method in Python?

While studying CS, I've noticed that some methods require you update and save the variable in order for the desired effect to kick in, while others just simply work when you execute the script.在学习 CS 时,我注意到有些方法需要您更新并保存变量才能发挥所需的效果,而另一些方法只是在您执行脚本时才起作用。

An example with the set stop_words and list lst :带有 set stop_words和 list lst的示例:

stop_words = stop_words.remove("whatever" ) # returns a variable of type none
stop_words.remove("whatever")  # has the desired effect of removing the word from the set
lst.append(2)  # doesn't update the list
lst = lst.append(2)  # updates the list.

What is the reason that I have to redeclare the lst variable when I use .append() but not when I want to use .remove() ?当我使用.append()而不是当我想使用.remove()时我必须重新声明lst变量的原因是什么?

TL;DR - only assign the result of an operation to a variable if the result is useful to you. TL;DR - 如果结果对您有用,则仅将操作结果分配给变量。

In python assignment, the expression on the right side of the equal sign is fully executed and resolved to a single anonymous object before the left hand side is evaluated for assignment.在 python 赋值中,等号右侧的表达式完全执行并解析为单个匿名 object,然后再评估左侧的赋值。 For example, suppose I perform a valid operation on the right hand side, but an invalid on one the left.例如,假设我在右侧执行了有效操作,但在左侧执行了无效操作。 The right side append worked even before python realized there was a problem on the left and raised an exception右侧 append 甚至在 python 意识到左侧有问题并引发异常之前就工作了

>>> lst1 = []
>>> lst2 =[1]
>>> lst1[1] = lst2.append(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>> lst1
[]
>>> lst2
[1, 2]

In a similar manner, set.remove and list.append modify their set and list respectively and return None.以类似的方式, set.removelist.append分别修改它们的 set 和 list 并返回 None。 They work exactly the same no matter what happens to the None later.无论以后 None 发生什么,它们的工作方式完全相同。

Both of your set examples remove "whatever" from the set.您的两个集合示例都从集合中删除了“任何东西”。 The difference is that in the first case you then rebind stop_words from the set to None .不同之处在于,在第一种情况下,您将stop_words从集合重新绑定为None If there are no other references to the set, it is deleted.如果没有对该集合的其他引用,则将其删除。 Same thing with the list.与列表相同。

stop_words = stop_words.remove("whatever") 
stop_words.remove("whatever")

This can be demonstrated by keeping a separate reference to the object to verify这可以通过单独参考 object 来验证

>>> test_set = {"whatever", "whatever 2"}
>>> stop_words = test_set
>>> stop_words = stop_words.remove("whatever")
>>> repr(stop_words)
'None'
>>> test_set
{'whatever 2'}
>>> stop_words = test_set
>>> stop_words.remove("whatever 2")
>>> stop_words
set()
>>> test_set
set()

The same thing happens with lists列表也会发生同样的事情

>>> test_list = []
>>> lst = test_list
>>> lst = lst.append(2)
>>> repr(lst)
'None'
>>> test_list
[2]
>>> lst = test_list
>>> lst.append(3)
>>> lst
[2, 3]
>>> test_list
[2, 3]

Lists are mutable, meaning that you calling a list method in itself will mutate it.列表是可变的,这意味着您调用列表方法本身会改变它。 For example, each of these will mutate the list without any re-assignments necessary.例如,这些中的每一个都将改变列表,而无需任何重新分配。

lst = [1, 2, 3]
print(f"Original list: {lst}")
lst.remove(1)
print(f"Updated: {lst}")
lst.append(4)
print(f"Updated: {lst}")

Output: Output:

original list: [1, 2, 3]
Updated: [2, 3]
Updated: [2, 3, 4]

The methods will return a None value (its only purpose is to mutate the list), so it is pointless to reassign it.这些方法将返回一个None值(它的唯一目的是改变列表),因此重新分配它是没有意义的。

lst = [1, 2, 3]
lst = lst.remove(1)
print(lst)

Output: Output:

None

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM