Python vars() 函式



**Python vars() 函式** 是一個 內建函式,它返回關聯物件的 **__dict__** 屬性。此屬性是一個字典,包含物件的所有可變屬性。我們也可以說此函式是訪問物件屬性的字典格式的一種方式。

如果我們在不帶任何引數的情況下呼叫 **vars()** 函式,則它的作用類似於 locals() 函式,並將返回一個包含區域性符號表的字典。

始終記住,每個 Python 程式都具有一個符號表,其中包含有關程式中定義的名稱(變數函式、類等)的資訊。

語法

Python **vars()** 函式的語法如下所示:

vars(object)

引數

Python **vars()** 函式接受單個引數:

  • **object** - 此引數表示具有 __dict__ 屬性的物件。它可以是模組、類或例項。

返回值

Python **vars()** 函式返回指定大小的 __dict__ 屬性。如果未傳遞任何引數,則它將返回區域性符號表。並且,如果傳遞的物件不支援 __dict__ 屬性,則它會引發 TypeError 異常。

vars() 函式示例

練習以下示例以瞭解 Python 中 **vars()** 函式的用法

示例:vars() 函式的用法

在使用者定義的類上應用 **vars()** 函式時,它會返回該類的屬性。在下面的示例中,我們定義了一個類和一個具有三個屬性的方法。並且,我們使用 **vars()** 函式顯示它們。

class Vehicle:
   def __init__(self, types, company, model):
      self.types = types
      self.company = company
      self.model = model
        
vehicles = Vehicle("Car", "Tata", "Safari")
print("The attributes of the Vehicle class: ")
print(vars(vehicles))

當我們執行上述程式時,它會產生以下結果:

The attributes of the Vehicle class: 
{'types': 'Car', 'company': 'Tata', 'model': 'Safari'}

示例:使用內建模組的 vars() 函式

如果我們對一個內建模組使用**vars()**函式,它將顯示該模組的描述。在下面的程式碼中,我們匯入了字串方法,並在**vars()**的幫助下,列出了該模組的詳細描述。

import string
attr = vars(string)
print("The attributes of the string module: ", attr)

以下是上述程式碼的輸出:

The attributes of the string module:  {'__name__': 'string', '__doc__': 'A collection of string constants......}

示例:使用vars()獲取使用者定義函式的屬性

在下面的示例中,我們建立了一個名為“newFun”的使用者定義方法,並嘗試使用**vars()**函式顯示其屬性。

def newFun():
   val1 = 10
   val2 = 20
   print(vars())

print("The attributes of the defined function:")
newFun()

上述程式碼的輸出如下:

The attributes of the defined function:
{'val1': 10, 'val2': 20}
python_built_in_functions.htm
廣告