Python vars() Method

The vars() method returns the __dict__ attribute of the specified object. A __dict__ object is used to store an object's writable attributes.

vars() Syntax:

vars(object)

Parameters:

object: (Optional) An object having the __dict__ attribute.

Return Value:

Returns the __dict__ value.

The following example demonstrates the vars() method.

Example: vars()
class student:
    def __init__(self):
        self.name = ''
        self.age=0

std = student()
print(vars(std))

std.name = 'Bill'
std.age = 18
print(vars(std))
Output
{'name': '', 'age': 0}
{'name': 'Bill', 'age': 18}

The vars() method raises an error if the class of the specified object does not have the __dict__() method. For example, non of the built-in class implements it, so passing built-in objects to vars() will raise an error, as shown below.

Example: vars()
print(vars('Hello World')) # raises TypeError
print(vars(10)) # raises TypeError
Output
TypeError: vars() argument must have dict attribute
TypeError: vars() argument must have __dict__ attribute