簡體   English   中英

如何在 python 中將變量稱為全局變量

[英]How can I refer to variable as global in python

我定義了一個全局變量,我想在 function 中更改/給出實際值。

當我嘗試運行它時,我收到一條錯誤消息,通知全局變量未定義。

請支持,謝謝。 這是我的代碼:


script_name = 'R2M_delayer.py'
recipe_name = 'R2M_E2E_delayer_NR_Ver_5.1'


global images
global metrology_images
logged_date = str(datetime.datetime.now()).split()[0]
NR_log = 'NR_' + logged_date + '.log'
images_output_dir_path = '/usr/local/insight/results/images/toolsDB/lauto_ptest_s' + str(datetime.datetime.now()).split()[0] + '/w3'
metro_images_dir_path = find_dir_path_delayer.get_delayer_images_dir_path()
metro_callback_dir_path = '/usr/local/disk2/unix_nt/R2M/RecipeRun'


def images_check():
    estimated_num_of_images = 6640  # Hard codded for Sanity wafer #3
    Actual_Images_List = os.listdir(images_output_dir_path)
    images = len(Actual_Images_List)

    if images >= estimated_num_of_images or images < 7000:
        return True, images
    print("\nImages quantity is not equal to the actual images in results folder.\n")
    return False

print('                 ' + str(images) + ' images were send.\n')

問題已解決。 我將全局變量定義為 class 中的字段,並重新評估了函數中字段的值。

global 關鍵字位於 function內部 這允許您在 function 之外調用該變量。 如果在 function 之外聲明變量,則不需要它。 順便說一句,你無論如何都要返回圖像。 返回值而不是修改全局變量要好得多,因為它可能會返回其引用。 全局變量不是一個好習慣,因為它可能會“搞砸”“”為您的程序分配的本地 memory。 我建議使用垃圾收集器庫gc.collect()來收集您沒有使用或管理的全局變量的任何數據。

  1. 在 function 定義中聲明全局變量,否則 function 中變量的 scope 總是局部的。
  2. 為了避免“變量未定義”錯誤,您可以在主代碼中使用一些默認值啟動它們,例如,images = None。
  3. 同意前面的回答,盡量不要使用全局變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM