Python vars() Function

Python3 内置函数Python3 Built-in Functions


vars()is a built-in function in Python for returning an object's__dict__attributes.

vars()Returns a dictionary containing all writable attributes of the object. For objects lacking__dict__a __dict__, a TypeError exception is raised.

Word Definitions: vars 是 variables(变量)的缩写。


Basic Syntax and Parameters

Syntax Format

vars(object)

Parameter Description

  • Parameter object:
    • Type: Any object
    • Description: The object whose attributes are to be obtained.

Function Description

  • Return Value: returns the object's__dict____dict__ dictionary.
  • Note: when called without arguments, it is equivalent to locals()locals()。

Examples

Example 1: Viewing Object 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 a dictionary of the object's instance attributes.
  2. Attributes can be accessed directly through the dictionary.

Example 2: Module and Class __dict__

Example

# The module's __dict__
import os
print(len(vars(os)))  # Output: the number of attributes of the os module

# The class's __dict__ (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__': ...}

Output:

vars() is very helpful for understanding object structure.

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


Python3 内置函数Python3 Built-in Functions


Other Extensions