這是Python中的內置函數。
用法:
vars(object)
vars()方法僅采用一個參數,該參數也是可選的。它以對象作為參數,可以是模塊,類,實例或具有__dict__屬性的任何對象。如果模塊,類,實例或任何其他對象具有__dict__屬性,則該方法返回__dict__屬性。如果對象與屬性匹配失敗,它將引發TypeError異常。對象(例如模塊和實例)具有可更新的__dict__屬性,但是其他對象可能對其__dict__屬性具有書麵限製。當傳遞空參數時,vars()的行為類似於locals()方法,這意味著本地字典僅對讀取有用,因為忽略了本地字典的更新。
# Python program to illustrate
# working of vars() method in Python
class Geeks:
def __init__(self, name1 = "Arun", num2 = 46, name3 = "Rishab"):
self.name1 = name1
self.num2 = num2
self.name3 = name3
GeeksforGeeks = Geeks()
print(vars(GeeksforGeeks))
輸出:
{'num2':46, 'name1':'Arun', 'name3':'Rishab'}
# Python program to illustrating
# the use of vars() and locals
# when no argument is passed and
# how vars() act as locals().
class Geeks(object):
def __init__(self):
self.num1 = 20
self.num2 = "this is returned"
def __repr__(self):
return "Geeks() is returned"
def loc(self):
ans = 21
return locals()
# Works same as locals()
def code(self):
ans = 10
return vars()
def prog(self):
ans = "this is not printed"
return vars(self)
if __name__ == "__main__":
obj = Geeks()
print (obj.loc())
print (obj.code())
print (obj.prog())
輸出:
{'ans':21, 'self':Geeks() is returned} {'ans':10, 'self':Geeks() is returned} {'num1':20, 'num2':'this is returned'}
相關用法
- Python map()用法及代碼示例
- Python cmp()用法及代碼示例
- Python ord()用法及代碼示例
- Python oct()用法及代碼示例
- Python hex()用法及代碼示例
- Python int()用法及代碼示例
- Python dir()用法及代碼示例
- Python now()用法及代碼示例
- Python sum()用法及代碼示例
- Python tell()用法及代碼示例
- Python id()用法及代碼示例
- Python globals()用法及代碼示例
注:本文由純淨天空篩選整理自Chinmoy Lenka大神的英文原創作品 vars() function in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。