What is the var() function in Python?

The var() function

The var() function is part of the standard library in Python and is used to get an object’s _dict_ attribute. The returned _dict_ attribute contains the changeable attributes of the object. This means that when we update the attribute list of an object, the var() function will return the updated dictionary.

Syntax

var(object)

Parameters

The object parameter is the only parameter of the function and is optional. object indicates the object whose defined parameters are to be returned.

Return value

The var() function returns a changeable _dict_ attribute of the passed object. This object can be a module, class instance, class, etc. When no parameter is passed, var() returns the local symbol table of the object passed as a dictionary.

A local symbol table is a data structure that is created by compilers that contain all local scope data required to execute a code block.

Code

In the code below, we define the class and give it some attributes. The Space class is saved in a variable SpaceTravel, which we call the var() function called on. The result is printed to the output and, as can be seen, is a dictionary.

# Python program to illustrate
# working of vars() method in Python
class Space:
def __init__(self, name1 = "Sputnik", num2 = 46, name3 = "Apollo"):
self.name1 = name1
self.num2 = num2
self.name3 = name3
SpaceTravels = Space()
print(vars(SpaceTravels))

Free Resources