如何檢查Python變數是否存在?


變數被定義為用於儲存某些資料的容器。它們代表一個記憶體位置。Python中的變數可以儲存任何型別的資料或值,包括整數、字串、浮點數、布林值等。

在Python中,定義程式中的變數時,不需要指定其資料型別。但是,在任何函式或應用程式可以使用變數之前,必須先定義它們。這可以透過簡單地將值賦給名稱來完成,如下所示:

x = 5

這裡,“x”是變數的名稱。此外,由於x儲存的是整數值,因此它是一個整型變數。

變數的作用域

變數可能並非在程式中的所有時候都可訪問。變數的宣告決定了這一點。變數作用域決定了在程式中可以在何處訪問識別符號。Python變數存在兩個基本作用域。

  • 區域性變數

  • 全域性變數

區域性變數

在程式碼塊中定義的變數通常只能在該程式碼塊內訪問。在程式碼塊外部無法訪問它們。這類變數稱為區域性變數。區域性變數的行為類似於形式引數識別符號。下面的例子說明了這一點。如果從它們的作用域之外訪問它們,則會觸發NameError異常。

示例

def greet():
   name = 'Rahul'
   print('Hello ', name)
greet()
print(name)

在上面的示例中,“name”是greet()函式的區域性變數,在函式外部無法訪問它。

輸出

Hello  Rahul
Traceback (most recent call last):
  File "main.py", line 5, in 
print(name)
NameError: name 'name' is not defined

全域性變數

全域性變數是在函式程式碼塊之外存在的變數。任何函式都可以訪問它的值。在定義函式之前,有必要初始化name變數。

name = 'Rahul'
def greet():
   print("Hello",name)
greet()

如果我們執行上面的簡單程式,則會產生如下結果。

輸出

Hello Rahul

驗證變數的存在

可以使用異常來檢查變數是否存在,但這並不推薦,因為我們並不總是知道是否定義了變數。在Python中檢查變數是否存在最安全、最優的方法是使用以下方法。

  • 使用**locals()**方法查詢變數在特定程式碼塊中是否存在。

  • 可以使用**globals()**方法確定變數在整個程式中的存在情況。

使用Locals()方法

將使用locals()函式驗證區域性變數的存在。在區域性名稱空間中,**locals()**返回一個字典,其中包含當前活動變數名稱作為鍵。

示例

在下面的示例中,定義了一個函式“local_func”,並建立了一個字串型別的區域性變數“var”。由於locals()方法返回包含當前區域性變數(以鍵的形式)的字典,因此我們可以使用“in”運算子來檢查變數是否存在。為了更準確,我們也可以在區域性名稱空間之外呼叫locals()方法來檢查其是否存在。

def local_func():
    var = "Test"
    if 'var' in locals():
        print ('variable found in local namespace')
    else:
        print ('variable not found in the local namespace')
local_func()
if 'var' in locals():
    print ('variable found in the global namespace')
else:
    print ('variable not found in the global namespace')

輸出

variable found in local namespace
variable not found in the global namespace

使用Globals()方法

使用globals()方法確定變數在全域性名稱空間中的狀態。此方法返回的字典中,全域性變數名稱表示為字串。

示例

可以使用“in”運算子在字典中檢查變數名字串。如果為真,則存在的變數是全域性名稱空間中存在的變數;否則,它不存在。

var = "Python" 
if 'var' in globals(): 
    print ("variable present in global namespace") 
else: 
    print ("variable does not present in global namespace")

輸出

variable present in global namespace

檢查變數是否存在於類中

可以使用**hasattr()**函式檢視變數是否存在於類中。如果物件包含給定名稱的屬性,則此方法的返回值為真;否則為假。

hasattr()方法的語法為:

hasattr(object, name)

示例

在下面的示例中,我們定義了一個包含描述其特徵的屬性的類“fruit”。使用hasattr()方法,我們檢查某些屬性是否存在;如果存在,則顯示它們的值。

class fruit:
    color = 'Red'
    name = 'Apple'
frt = fruit()
if hasattr(frt, 'name'):
    print("Fruit's name:", frt.name)
if hasattr(frt, 'color'):
    print("Fruit's color:", frt.color)

輸出

Fruit's name: Apple
Fruit's color: Red

示例

讓我們看另一個例子,檢查變數是否存在於Python程式中。

x =10
class foo:
   g = 'rt'
   def bar(self):
      m=6
      if 'm' in locals():
         print ('m is local variable')
      else:
         print ('m is not a local variable')
f = foo()
f.bar()
if hasattr(f, 'g'):
   print ('g is an attribute')
else:
   print ("g is not an attribute")
if 'x' in globals():
   print ('x is a global variable')

輸出

執行上面的程式後,輸出顯示如下:

m is local variable
g is an attribute
x is a global variable

更新於:2023年2月22日

19K+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始
廣告