內置函數var()
用于返回指定對象的 dict 屬性。dict 屬性是一個具有對象的可變或可寫屬性的字典。
**vars(object)** #where object can be module, class, instance etc
vars()
參數:
接受單個參數。如果給定對象的 dict 屬性不可用,則會引發類型錯誤異常。如果沒有傳遞參數,這個函數的行為類似于locals()
函數。
參數 | 描述 | 必需/可選 |
---|---|---|
目標 | 可以是模塊、類、實例或任何具有 dict 屬性的對象 | 需要 |
var()
返回值
vars()
函數的輸出是一個字典。如果我們更新 object dict 字典值,那么vars()
函數將返回更新后的值。
| 投入 | 返回值 | | If 對象 | dict 屬性 |
Python 中vars()
方法的示例
示例vars()
在 Python 中是如何工作的
class Fo:
def __init__(self, a = 25, b = 30):
self.a = a
self.b = b
Foobject = Fo()
print(vars(Foobject))
輸出:
{'a': 25, 'b': 30}
示例 python var()
的工作原理
class Persondet:
name = "John"
age = 36
country = "Italy"
x = vars(Persondet)
print(x)
輸出:
{'__module__': '__main__', 'name': 'John', 'age': 36, 'country': 'Italy', '__dict__': <attribute>, '__weakref__': <attribute>, '__doc__': None}</attribute></attribute>