Python 变量不会在模块外更新

Python variable won't update outside of module

我有一个名为 store_number 的变量,我从 main.py 传入一个名为 store_selector 的模块,该模块递增商店编号,直到找到有效的商店。整个事情是在一个 while 循环中进行的,在第一个循环之后,store 变量不会保留它来自 store_selector 模块的更新值,而是恢复到它的原始值。我知道这与声明一个全局变量有关,但问题是如果我在模块内声明一个全局变量,我假设它会在调用该模块时继续分配初始值(因为它在 main.py)

有什么想法吗?

里面main.py

store_number = 103

while store_number < 10000:
    store_dropdown(driver)
    store_selector(driver, store_number)
    item_inspector(driver)

里面functions.py

def store_selector(driver, store_number):
    textbox = driver.find_element(By.ID, "myStore-formInput")
    #time.sleep(1)
    store_number += 1
    textbox.send_keys(store_number, Keys.RETURN)
    time.sleep(1)
    while driver.find_element(By.ID, "myStore-errorMessage").is_displayed() and store_number < 10000:
        store_number += 1
        textbox.clear()
        textbox.send_keys(store_number, Keys.RETURN)
        time.sleep(1)
    else:
        store_button = driver.find_element(By.CSS_SELECTOR, f'button[data-storeid="{str(store_number).zfill(4)}"]')
        store_button.click()

您只需将 store_number+=1 移动到您的主脚本中即可

store_number = 103

while store_number < 10000:
    store_dropdown(driver)
    store_selector(driver, store_number)
    item_inspector(driver)
    store_number+=1

或者如果你在store_selector中坚持这样做,return主函数的增量值

store_number = 103

while store_number < 10000:
    store_dropdown(driver)
    store_number = store_selector(driver, store_number)
    item_inspector(driver)

def store_selector(driver, store_number):
    store_number += 1

    ########
    # Your function
    ########

    return store_number

你真的应该使用第一个解决方案,除非你有很好的理由在函数中增加你的计数器(即有条件的增加)