Python vars Function with Examples

In Python, the vars function is frequently utilized to retrieve the dict attribute associated with a specified object.

Python vars Function Syntax

It has the following syntax:

Example

vars(object)

Parameters

  • object (optional): This refers to an object that can consist of a module, class, instance, or any other entity that possesses a dict attribute.
  • Return

It retrieves the dict attribute of the specified object. If any object does not correspond to the attribute, it triggers a TypeError exception.

Python vars Function Example

The example provided below demonstrates how the vars function operates in Python.

Example

class Python:

  def __init__(self, x = 7, y = 9):

    self.x = x

    self.y = y

InstanceOfPython = Python()

print(vars(InstanceOfPython))

Output:

Output

{'y': 9, 'x': 7}

Explanation:

In the preceding example, we establish a class called Python and create an instance of the Python class named InstanceOfPython. As a result, it outputs the dict attribute associated with the objects x and y.

Input Required

This code uses input(). Please provide values below: