Python 中的 vars() 函式
vars() 函式屬於 Python 標準庫提供的內建函式集合。它將關聯物件的 __dic__ 屬性返回到控制檯。
語法
vars(object)
返回值型別
<Dictionary Type>
引數
vars() 函式只接受一個引數。它將一個物件作為其引數,該物件可以是任何模組、類或任何與之關聯的 __dict__ 屬性的物件。
此引數是可選的。如果函式在沒有引數的情況下使用,則會顯示包含本地符號表的字典。
涉及的異常
如果傳遞的引數與屬性不匹配,則會引發 TypeError 異常。
範圍
當沒有傳遞引數時,Vars() 的作用類似於 locals() 方法。locals() 方法修改並返回當前存在的本地符號表的字典。
工作機制
<類名> 與 __name__ 屬性關聯;bases 元組使用基類進行逐項列出,並關聯 __bases__ 屬性,字典是包含類體中定義的當前名稱空間,並將其複製到標準字典型別以顯示為 __dict__ 屬性。
讓我們討論一些示例,以便我們能夠掌握 vars() 函式的概念
示例
class test: def __init__(self, integer_1=555, integer_2=787): self.integer_1 = integer_1 self.integer_2 = integer_2 obj_test = test() print(vars(obj_test))
輸出
{'integer_1': 555, 'integer_2': 787}
示例
class sample: company = "Tutorial's Point " Number = 4 Topic = "Python 3.x." obj = vars(sample) print(obj)
輸出
{'__doc__': None, '__weakref__': <attribute '__weakref__' of 'sample' objects>, 'Topic': 'Python 3.x.', 'company': "Tutorial's Point ", '__module__': '__main__', 'Number': 4, '__dict__': <attribute '__dict__' of 'sample' objects>}
示例
class test(): # Python __repr__() function returns the representation of the object. # It may contain any valid expression such as tuples, list, dictionary, string, set etc def __repr__(self): return "Tutorial's point" def localvariables(self): number = 4 return locals() if __name__ == "__main__": obj = test() print (obj.localvariables())
輸出
{'self': Tutorial's point, 'number': 4}
解釋
第一個示例程式碼描述了與類的建構函式關聯的 __dict__ 屬性的使用,並在建構函式方法中設定了預設值。4
第二個示例程式碼描述了與類本身關聯的 __dict__ 屬性的使用,其中 __doc__ 屬性為空。
第三個示例程式碼描述了與類內部的使用者定義函式關聯的 __dict__ 屬性的使用,以及在本地範圍內的變數。
結論
在本文中,我們學習瞭如何在 Python 3.x 或更早版本中在各種情況下實現 vars 函式。您可以實現相同的演算法,以便在需要時使用 vars 函式。
廣告