Python vars() Function
vars() is a built-in function in Python used to return an object's __dict__ attributes.
vars() Returns a dictionary containing all writable attributes of the object. For objects without a __dict__ attribute, a TypeError exception is raised.
Word meaning: vars 是 variables(变量)的缩写。
Basic syntax and parameters
Syntax format
vars(object)
Parameter Description
- Parameter object:
- Type: any object
- Description: the object whose attribute is wanted.
Function description
- Return Value: Returns the object's
__dict__dictionary. - Note: Without arguments it is equivalent to
locals()。
Example
Example 1: viewing an object's attributes
Example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Tom", 20)
# View the object's __dict__
print(vars(p))
# Output: {'name': 'Tom', 'age': 20}
# Access the dictionary
print(vars(p)["name"]) # Output: Tom
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Tom", 20)
# View the object's __dict__
print(vars(p))
# Output: {'name': 'Tom', 'age': 20}
# Access the dictionary
print(vars(p)["name"]) # Output: Tom
Expected output:
{'name': 'Tom', 'age': 20}
Tom
Code analysis:
- vars() returns the instance attribute dictionary of an object.
- Attributes can be accessed directly through the dictionary.
Example 2: __dict__ of modules and classes
Example
# __dict__ of a module
import os
print(len(vars(os))) # Output: number of attributes of the os module
# __dict__ of a class (excluding instance attributes)
class MyClass:
class_attr = 100
def __init__(self):
self.instance_attr = 200
print(vars(MyClass))
# Output: {'__module__': '__main__', 'class_attr': 100, '__init__': ...}
import os
print(len(vars(os))) # Output: number of attributes of the os module
# __dict__ of a class (excluding instance attributes)
class MyClass:
class_attr = 100
def __init__(self):
self.instance_attr = 200
print(vars(MyClass))
# Output: {'__module__': '__main__', 'class_attr': 100, '__init__': ...}
Result:
vars() is very helpful for understanding object structure.
vars() It is often used for debugging and dynamic attribute access.
Python3 built-in function