python-3.x - 为什么有必要澄清我的变量在这种情况下是全局的?
问题描述
所以我拼凑了一个家务分配程序。每次你运行它时,它都会随机分配我和我室友之间的家务活。没有一个家务会连续超过 2 周分配给同一个人。无论如何,我很难让它工作,因为这是我的第一个 python 项目,但我认为它现在运行完美。
我的问题是,在我的 choreAssign() 函数中,如果我没有将我的变量澄清为全局变量,我会在第 50-55 行得到一个“未解决的引用”错误。这是为什么?(请记住,我还是新手/正在学习,我的所有研究都没有给出明显的答案)。
整个代码如下。代码中的一个很大的注释是澄清第 50 行的开始位置。我的代码相对较短,所以我认为可以发布整个内容。这是我在这个网站(或任何类似的网站)上的第一篇文章,所以如果缺少一些礼仪,我很抱歉。
import random
chores = ("Shower", "Kitchen counters", "Floors", "Toilet", "Mirror and Sink", "Tables/Laundry", "Garden", "Fan")
# Chore lists to be assigned this week
nick_chores1 = []
raul_chores1 = []
# Chore list for last week
nick_chores2 = []
raul_chores2 = []
# Chore list for week before last
nick_chores3 = []
raul_chores3 = []
# Extra chores that have already been repeated the last two weeks
chores_extra = []
def choreAssign():
# GLOBAL VALUES IN QUESTION
global nick_chores3
global nick_chores2
global raul_chores3
global raul_chores2
local_chores = list(chores)
y = len(local_chores)
while len(nick_chores1) < y / 2:
random_chore = random.choice(local_chores)
if len(nick_chores3) > 0:
if nick_chores2.count(random_chore) + nick_chores3.count(random_chore) < 2:
nick_chores1.append(random_chore)
local_chores.remove(random_chore)
else:
chores_extra.append(random_chore)
local_chores.remove(random_chore)
else:
nick_chores1.append(random_chore)
local_chores.remove(random_chore)
print(chores_extra)
raul_chores1.extend(local_chores)
raul_chores1.extend(chores_extra)
local_chores.clear()
chores_extra.clear()
print("Nick's chores for the week are: " + str(nick_chores1))
print("Raul's chores for the week are: " + str(raul_chores1))
# LINE 50 STARTS AFTER THESE COMMENTS. The below comment just clarifies what I'm trying to do with these few lines of code
# the below 6 lines move the weekly data back one week (ex week 2 moves to week 3)
nick_chores3 = nick_chores2[:]
raul_chores3 = raul_chores2[:]
nick_chores2 = nick_chores1[:]
raul_chores2 = raul_chores1[:]
nick_chores1.clear()
raul_chores1.clear()
x = input('Type "New" to assign a new weeks worth of chores: ').upper()
if x == "NEW":
choreAssign()
choreAssign()
解决方案
因为函数内部的变量只存在于函数结束之前。将它们声明为全局允许它们被保存而不是垃圾收集。如果您想拥有具有不同属性的不同对象或方法等,这很有用。如果您不想使用全局,您可以创建一个类,将要在方法/类之外使用的变量声明为该类的属性。如果您需要进一步解释,请发表评论:)
推荐阅读
- laravel - PayPal Laravel Integrarion CheckOutStatus = PayentActionNotIntiated
- hashicorp-vault - Unable to connect to Vault Error unsealing: Put "https://127.0.0.1:8200/v1/sys/unseal": dial tcp 127.0.0.1:8200: connect: connection denied
- google-apps-script - 使用服务帐户进行身份验证的 Google 环聊机器人(Apps 脚本)
- python - 将预测结果与标签相关联
- python - 在一个图形子图中合并由不同散点图制作的多个路径集合
- android - 使用多风格编译 GMS 和 HMS 包。但是GMS版本编译的时候报错
- javascript - 如何在 Spring Boot 中将访客购物车与登录的用户帐户合并?
- python - 尝试使用 selenium 检索文本时出错
- r - 如何构建我的 R 包,以便我可以快速调整一些样式更改(例如主要颜色/字体大小)
- python - 如何将自我属性传递给装饰器?