What is the use of var() and dir() functions?

Last updated 3 weeks, 5 days ago | 22 views 75     5

Tags:- Python

Python | var() and dir()

The vars() function returns the __dict__ attribute of an object. and  The dir() function returns all properties and methods of the specified object, without the values.



The var() function is part of the standard library in Python and is used to get an object’s _dict_ attribute. The returned  _dict_  attribute contains the changeable attributes of the object. This means that when we update the attribute list of an object, the var() function will return the updated dictionary.

class Student:
    name = "John"
    age = 36
    country = "norway"

x = vars(Student)



The dir() function tries to return a valid list of attributes and methods of the object it is called upon. It behaves differently with different objects, as it aims to produce the most relevant data, rather than the complete information.

  • For Modules/Library objects, it returns a list of all attributes, contained in that module.
  • For Class Objects, it returns a list of all valid attributes and base attributes.
  • With no arguments passed, it returns a list of attributes in the current scope.
class Student:
    name = "John"
    age = 36
    country = "Norway"