Python vars() function

Published February 17, 2022

The Python vars() method is used to obtain the __dict__ attribute for the specified class, module, instance, or other object containing a __dict__ attribute.
The _dict_ attribute is used to represent the dictionary or any other python mapping object that is used to store the object attributes.

Syntax
Let's look at the syntax  for the Python var() method

vars(object)


vars() accepts a single parameter, which is also optional. This object can be a class, a module, an instance, or anything with a _dict_attribute.


Example

Here is an example of the var() function:

class Customer:
    def __init__(self, products = 'POS System', budget ='$4000', nationality = 'Indian', buying_behavior = 'Frequent buyer'):
        self.Products = products
        self.Budget = budget
        self.Nationality = nationality
        self.Buying_behavior = buying_behavior
my_object = Customer()
print('Our Cudtomer Dictionary has:', vars(my_object))
class Customer:
    def __init__(self, products = 'POS System', budget ='$4000', nationality = 'Indian', buying_behavior = 'Frequent buyer'):
        self.Products = products
        self.Budget = budget
        self.Nationality = nationality
        self.Buying_behavior = buying_behavior
my_object = Customer()
print('Our Cudtomer Dictionary has:', vars(my_object))


Output

Our Cudtomer Dictionary has: {'Products': 'POS System', 'Budget': '$4000', 'Nationality': 'Indian', 'Buying_behavior': 'Frequent buyer'}
Our Cudtomer Dictionary has: {'Products': 'POS System', 'Budget': '$4000', 'Nationality': 'Indian', 'Buying_behavior': 'Frequent buyer'}

 

 

Download Source code

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

197 Views