Tutorial Study Image

Python vars()

The built-in function var() is used to return __dict__ attribute of the specified object.The __dict__ attribute is a dictionary having changeable or writable attributes of the object.

vars(object) #where object can be module, class, instance etc

vars() Parameters:

Takes a single parameter. If the __dict__ attribute is not available for the given object it raises a TypeError exception. This function acts like the locals() function if no argument is passed.

Parameter Description Required / Optional
object  can be module, class, instance, or any object having the __dict__ attribute Required

vars() Return Value

The output of vars() function is a dictionary.If we update the object __dict__ dictionary values, then vars() function returns the updated value.

Input Return Value
 If object __dict__ attribute

Examples of vars() method in Python

Example 1: How vars() works in Python

class Fo:
  def __init__(self, a = 25, b = 30):
    self.a = a
    self.b = b
Foobject = Fo()


{'a': 25, 'b': 30}

Example 2:working of python var()

class Persondet:
  name = "John"
  age = 36
  country = "Italy"

x = vars(Persondet)




{'__module__': '__main__', 'name': 'John', 'age': 36, 'country': 'Italy', '__dict__': , '__weakref__': , '__doc__': None}