Python vars() Function with Examples

vars() Function in Python:

The vars() function returns an object’s __dict__ attribute.

The __dict__ attribute is a dictionary that contains a list of the object’s changeable attributes.

Note:

It should be noted that calling the vars() function without any parameters will result in the return of a dictionary containing the local symbol table.

Syntax:

vars(object)

Parameters

object: It may be Any object that has the __dict__ attribute.

Return Value:

vars() returns the given object’s __dict__ attribute.

  • If the object passed to vars() does not have the __dict__ attribute, a TypeError exception is thrown.
  • If no arguments are passed to vars(), it behaves similarly to the locals() function.

Note: It should be noted that __dict__ refers to a dictionary or a mapping object. It stores the (writable) attributes of an object.

vars() Function with Examples in Python

Method #1: Using Built-in Functions (Static Input)

Approach:

  • Create a class say Employee.
  • Take a variable and initialize it with some random number(eid).
  • Take another variable and initialize it with some random name(ename).
  • Take another variable and initialize it with some random job role(jobrole).
  • Create an object for the above class and apply the vars() method to it.
  • Store it in a variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Create a class say, Employee.
class Employee:
    # Take a variable and initialize it with some random number(eid).
    eid = 5
    # Take another variable and initialize it with some random name(ename).
    ename = "kevin"
    # Take another variable and initialize it with some random job role(jobrole).
    jobrole = "software developer"


# Create an object for the above class and apply the vars() method to it
# Store it in a variable.
rslt = vars(Employee)
# Print the above result.
print(rslt)

Output:

{'__module__': '__main__', 'eid': 5, 'ename': 'kevin', 'jobrole': 'software developer', '__dict__': <attribute '__dict__' of 'Employee' objects>, '__weakref__': <attribute '__weakref__' of 'Employee' objects>, '__doc__': None}