本地变量在Python中赋值之前被引用,当我设置它的全局 [英] local variable referenced before assignment in python when i set it global

查看:606
本文介绍了本地变量在Python中赋值之前被引用,当我设置它的全局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 随机导入randint 
转换= [4,4.2,5,6,7]
days_names = ['Sunday','Monday','Tuesday ','星期三','星期四']
workers_names = ['Itai','Or','Reut','Kuka','Aviel']
counter = 1

def shift_arrange(worker):day.values()中的

计数器+ = 1
全球avilable_shifts
avilable_shifts = check_avilable_shifts(日)
如果不是random_shifte_selector(worker,day):soft_reset(worker)

我将counter设置为全局变量,我尝试运行这段代码,我得到了局部变量错误:

pre code> Traceback(最近一次调用最后一次):
文件C:\或\\\\\\\\\\\\\\\\\\\\ shiftshift.py
for workers.values():shift_arrange(w)
在shift_arrange $ b文件C:\Or\mypy\shift creator\shift cretor.py,第105行$ b counter + = 1
UnboundLocalError:赋值前引用的局部变量'counter'

我看到有些人在这里问这个问题,他删除了他的pyc文件或其他东西(我不知道它是什么),它的工作很好。为什么会发生?它不会发生在程序中的其他变量。



谢谢,或者

解决方案

您需要声明一个全局变量

pre $ c $ def def_arrange(worker)
全局计数器
day.values():
counter + = 1
...



<由于您在该范围内修改了 counter ,因此python会将其视为局部变量,除非您声明它为 global 。如果您只需要阅读它,那就没有必要了。



请考虑以下内容:



$ p code code code $ c

$($) b $ b

虽然这不是:

  c = 0 
def f():
print c
c = 1
f()
pre>

尽管如此:

  c = 0 
def f():
global c
print c
c = 1
f()
print c#打印1,f()修改全局值


from random import randint
shifts = [4, 4.2, 5, 6, 7]
days_names = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday']
workers_names = ['Itai', 'Or', 'Reut', 'Kuka', 'Aviel']
counter = 1

def shift_arrange(worker):
    for day in days.values():
        counter+=1
        global avilable_shifts
        avilable_shifts = check_avilable_shifts(day)
        if not random_shifte_selector(worker,day): soft_reset(worker)

I set counter as a global variable, and when i try to run this code i get the local variable error:

Traceback (most recent call last):
  File "C:\Or\mypy\shift creator\shift cretor.py", line 144, in <module>
    for w in workers.values(): shift_arrange(w)
  File "C:\Or\mypy\shift creator\shift cretor.py", line 105, in shift_arrange
    counter+=1
UnboundLocalError: local variable 'counter' referenced before assignmen

I saw some guy ask this question here, he deleted his pyc file or something(i don't know what is it) and its work fine. Why this is happen? Its not happen to other variables in the program.

Thanks, Or

解决方案

You need to declare a global variable

def shift_arrange(worker):
    global counter
    for day in days.values():
        counter+=1
        ...

Since you modify counter in that scope, python treats it as a local variable, unless you declare it as global. If you only need to read it, that isn't necessary.

Consider the following:

This works:

c = 0
def f():
   print c
f()

While this does not:

c = 0 
def f():
  print c
  c = 1
f()

While this does:

c = 0
def f():
  global c
  print c
  c = 1
f()
print c  # prints 1, f() modified the global value

这篇关于本地变量在Python中赋值之前被引用,当我设置它的全局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆