我的全局变量没有在其他功能发现

问题描述 投票:0回答:1

我给你remaining_length股票长度的价值。股票长度在另一个函数分配的,也是全球性的。我尝试运行代码,并告诉我,我使用分配前的变量。我宣布,通过我的代码使用其它全局变量并没有这个问题,到现在为止。另外,为什么没有承认我的全局变量all_possible_cutting_options,但不remaining_length?我搬到remaining_lengthget_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
python python-3.x global-variables
1个回答
0
投票

问题是,虽然remaining_length是你的第一个全球性的功能,它在你的第二个地方。这是因为分配给remaining_lengthremaining_length -= cut.length * cut.quantity)。为了解决这个问题,只需添加一个global声明,大意是功能以及:

def get_next_possible_cutting_option():
    global remaining_length
© www.soinside.com 2019 - 2024. All rights reserved.