Python built-in Method - vars()

The vars() method is a built-in function in Python that returns the __dict__ attribute of an object. This attribute is a dictionary containing the object's attributes and their values.

Here is the syntax for the vars() method:

vars([object])
Sou‮:ecr‬www.theitroad.com

The object parameter is optional. If it is not specified, vars() returns the local namespace as a dictionary. If object is specified, vars() returns the __dict__ attribute of the object.

Here are some examples of using the vars() method:

class MyClass:
    def __init__(self):
        self.x = 5
        self.y = 10

obj = MyClass()

print(vars())    # output: {...}
print(vars(obj))    # output: {'x': 5, 'y': 10}

In the first example, we call the vars() method without specifying an object, so it returns the local namespace as a dictionary. In this case, the output will depend on the variables defined in the local scope.

In the second example, we define a custom class MyClass with two attributes x and y. We then create an instance of the class and store it in the variable obj. We then call the vars() method with obj as the parameter, so it returns the __dict__ attribute of the object as a dictionary containing the values of the x and y attributes.

The vars() method is useful when you need to access the attributes and their values of an object dynamically. This can be especially useful when working with objects whose attributes are not known in advance, or when you need to introspect the attributes of an object for debugging or analysis purposes.