vars () function in Python

Python Methods and Functions

This is a built-in function in Python. 
Syntax :

vars(object)

The vars () method only takes one parameter, and that too not necessary. It takes an object as a parameter, which can be a module, class, instance, or any object that has a __dict__ attribute.
The method returns a __dict__ attribute for a module, class, instance, or any other object if the same has the __dict__ attribute.  If the object does not match the attribute, it raises a TypeError . Objects such as modules and instances have an updatable __dict__ attribute, however other objects may have written restrictions on their __dict__ attributes.  vars () acts like the locals () method when passed an empty argument which implies that the locals dictionary is read-only useful since updates to the locals dictionary are ignored.

# Python program for illustration
# how vars () works in Python

 

class Geeks:

def __ init __ ( self , name1 = "Arun" , num2 = 46 , name3 = "Rish ab " ):

  self . name1 = name1

self . num2 = num2

self . name3 = name3

 

Python.Engineering = Geeks ()

print ( vars (GeeksforGeeks))

Output:

 {'num2': 46,' name1': 'Arun',' name3': 'Rishab'} 

< / p>

# Python illustration program
# using vars () and locals
# when no argument is passed and
# like vars () act like local ().

class Geeks ( object ):

def __ init __ ( self ):

self . num1 = 20

self . num2 = " this is returned "

  

def __ repr __ ( self ):

return "Geeks () is returned"

 

def loc ( self ):

ans = 21

return locals ()

  

  # Works the same as local ()

  def code ( self ):

ans = 10

return vars ()

  

def prog ( self ):

ans = "this is not printed"

return vars ( self )

 

 

if __ name__ = = "__ main__" :

obj = Geeks ()

  print (obj.loc ())

print (obj.code ())

print (obj.prog ())

Output:

 {'ans': 21,' self': Geeks () is returned} {'ans': 10,' self': Geeks () is returned} {'num1': 20,' num2': 'this is returned'} 




Tutorials