Python’s vars() Function

Learn Python @ Freshers.in

In Python, the vars() function is a powerful tool for accessing an object’s attributes or creating dictionaries from objects. This article aims to provide a comprehensive guide on its usage, applications, and significance through detailed examples.

Understanding vars() Function

The vars() function in Python is utilized to access an object’s attributes or convert objects into dictionaries. Its syntax is straightforward:

vars(object)

Here, object represents the object whose attributes are to be accessed.

Example 1: Accessing Object’s Attributes

class MyClass:
    def __init__(self, name, age):
        self.name = name
        self.age = age

obj = MyClass("John", 30)
attributes = vars(obj)
print("Object's attributes:", attributes)

Output 1:

Object's attributes: {'name': 'John', 'age': 30}

Example 2: Modifying Object’s Attributes

class MyClass:
    def __init__(self, name, age):
        self.name = name
        self.age = age

obj = MyClass("John", 30)
attributes = vars(obj)
attributes['age'] = 35
print("Modified attributes:", attributes)
print("Modified age:", obj.age)

Output 2:

Modified attributes: {'name': 'John', 'age': 35}
Modified age: 35

Example 3: Creating Dictionary from Object

class MyClass:
    def __init__(self, name, age):
        self.name = name
        self.age = age

obj = MyClass("John", 30)
obj_dict = vars(obj)
print("Dictionary from object:", obj_dict)

Output 3:

Dictionary from object: {'name': 'John', 'age': 30}

Points to Remember

  • The vars() function is used to access an object’s attributes or create dictionaries from objects.
  • It returns a dictionary representing the object’s attributes.
  • Changes made to the dictionary returned by vars() reflect changes in the object’s attributes.
Author: user