在另一个函数中找不到我的全局变量

时间:2019-02-10 19:26:16

标签: python python-3.x global-variables

我为remaining_length分配了库存长度的值。库存长度在另一个功能中分配,并且也是全局的。我尝试运行代码,并告诉我在赋值之前我正在使用变量。我已经通过我的代码声明并使用了其他全局变量,直到现在还没有出现此问题。另外,为什么它不能识别我的全局变量all_possible_cutting_options却不能识别remaining_length?我将remaining_length移到了get_next_possible_cutting_option()并可以使用,但是我需要保存remaining_length的值并在下次调用get_next_possible_cutting_option()时再次使用它,而不是重置该值每次回到stock_length

def get_all_possible_cutting_options_for_a_bar():
    global all_possible_cutting_options
    global remaining_length
    remaining_length = stock_length
    all_possible_cutting_options = []
    another_cutting_option_possible = get_another_cutting_option_possible()
    while another_cutting_option_possible:
        get_next_possible_cutting_option()
        another_cutting_option_possible = get_another_cutting_option_possible()

def get_next_possible_cutting_option():
    cutting_option = []
    for cut in cuts_ordered:
        if remaining_length >= cut.length:
            cut.quantity = remaining_length // cut.length
            remaining_length -= cut.length * cut.quantity
            cutting_option.append(cut)
        else:
            cut.quantity = 0
            cutting_option.append(cut)
    all_possible_cutting_options.append(cutting_option)

错误:

Traceback (most recent call last):
  File "main-v3.0.py", line 91, in <module>
    get_all_possible_cutting_options_for_a_bar()
  File "main-v3.0.py", line 41, in get_all_possible_cutting_options_for_a_bar
    get_next_possible_cutting_option()
  File "main-v3.0.py", line 56, in get_next_possible_cutting_option
    if remaining_length >= cut.length:
UnboundLocalError: local variable 'remaining_length' referenced before assignment

1 个答案:

答案 0 :(得分:0)

问题在于,尽管remaining_length在您的第一个函数中是全局的,但在第二个函数中是 local 的。这是因为您分配remaining_lengthremaining_length -= cut.length * cut.quantity)。要解决此问题,只需在该函数中添加一个global声明:

def get_next_possible_cutting_option():
    global remaining_length