Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python vars() Function

Python vars() Function

Python3 Built-in Functions Python3 built-in 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

Function description


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

Expected output:

{'name': 'Tom', 'age': 20}
Tom

Code analysis:

  1. vars() returns the instance attribute dictionary of an object.
  2. 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__': ...}

Result:

vars() is very helpful for understanding object structure.

vars() It is often used for debugging and dynamic attribute access.


Python3 Built-in Functions Python3 built-in function