【发布时间】:2020-04-10 00:49:25
【问题描述】:
我目前正在参加有关 Python 编程的在线 Udemy 课程,我们正在学习搁置模块。教授已经表明,由于某种原因,搁置者无法知道可变对象何时发生了这样的变化:(他也解释了解决方法)
import shelve
# Making a bunch of lists to bind to shelves later
blt = ["bacon", "tomato", "lettuce", "bread"]
beans_on_toast = ["beans", "bread"]
scrambled_eggs = ["eggs", "butter", "milk"]
soup = ["tin of soup"]
pasta = ["pasta", "cheese"]
with shelve.open('recipes') as recipes:
# Binding each list to a shelve
recipes['blt'] = blt
recipes['beans on toast'] = beans_on_toast
recipes['scrambled eggs'] = scrambled_eggs
recipes['pasta'] = pasta
recipes['soup'] = soup
# Attempting to append 'butter' and 'tomato' to respective lists
recipes['blt'].append("butter")
recipes['pasta'].append("tomato")
for snack in recipes:
print(snack, recipes[snack])
for 循环的输出显示货架没有改变,并且值 'butter' 和 'tomato' 没有附加到它们各自的货架上。
我的在线教授试图解释为什么会这样,但我无法理解。如果有人可以尝试向我解释,我将不胜感激。
如果您有耐心,您能否解释一下您在回答中可能使用的任何您认为我不会理解的术语。我还是个初学者,Python 是我学习的第一门语言。提前致谢!
【问题讨论】:
-
它怎么会知道?你有没有想到一个特定的机制?
-
机制?我只是想知道为什么我对书架的更新没有反映在输出中。
-
通过什么方式你希望书架知道你的更新吗?
-
我认为 .append 方法可以做到。