The vars()
method is a built-in Python function that returns the __dict__
attribute of an object.
The syntax for the vars()
method is as follows:
vars(object)
The vars()
method only takes one required parameter, which is an object. The object can be a class, module, instance, etc.
The return value is the __dict__
attribute. However, if the object does not have any such attribute, the function raises a TypeError
.
In the code below, the vars()
function returns the key-value pair of the class object in the first case.
Note: When an argument with no
__dict__
attribute is passed into thevars()
function, the function gives an error.
# dict attribute presentclass School:def __init__(self, section1 = 55, section2 = 73):self.x = section1self.y = section2object = School()print('Class object:', vars(object))# dict attribute absentprint('List object', vars([1,2,3]))