vars() Built-in Function

Python – vars()

Python vars() built-in function is used to get the __dict__ attribute of an object if it exists.

vars() built-in function can be used for debugging, dynamic attribute access, or converting objects to dictionaries, etc.

In this tutorial, we will learn the syntax and usage of vars() built-in function, and cover the above said scenarios with examples.

Syntax

The syntax of vars() function is

vars(object)

where

Parameter Description
object Any Python object.

Examples

1. Get attributes of an object as dictionary

In the following program, we define a class named Student with two attributes. We create a new object of type Student, and then using vars() built-in function, we shall get the attributes and their values as a dictionary. attribute is the key, and its value if the respective value for the key.

Python Program

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

# Create an object of type Student
student1 = Student("Ram", 12)

# Get attributes of the object as a dictionary
attributes = vars(student1)
print(attributes)
Run Code

Output

{'name': 'Ram', 'age': 12}

Uses of vars()

vars() built-in function can be used for the following purposes.

Summary

In this Built-in Functions tutorial, we learned the syntax of the frozenset() built-in function, and how to use this function to create a frozenset object.

Related Tutorials

Privacy Policy Terms of Use

SitemapContact Us