如何檢查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()**函式檢視變數是否存在於類中。如果物件包含給定的命名屬性,則此方法的返回值為true;否則為false。

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+ 次瀏覽

啟動您的職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.