__dict__ attribute and vars() Function in Python

Every module has a unique property called __dict__. This dictionary contains the symbol table for the module. The (writable) characteristics of an item are stored in a dictionary or the other mapping object.

To put it simply, every object in Python has a property that is indicated by the symbol __dict__. Furthermore, this object has every property that has been specified for it. Another name for __dict__ is mappingproxy object. We can use the dictionary via applying the __dict__ property to a class object.

Syntax :

object.__dict__  

Example :

class AnimalClass:  
    def __init__(self,identity,age):  
        self.identity = identity  
        self.age = age  
      
    def feature(self):  
        if self.age == "10":  
            return True  
        else:  
            return False  
ac = AnimalClass('Lion','10')  
print(ac.__dict__)  

Output:

{'identity': 'Lion', 'age': '10'}

Example 2 :

This example will demonstrate that by the means of the __dict__ attribute, one could create a dictionary out of any object :

# class Flowers is defined  
class Flowers:  
      
    # constructor  
    def __init__(self):  
          
        # keys are being initialized with  
        # their corresponding values  
        self.Rose = 'red'  
        self.Lily = 'white'  
        self.Lotus = 'pink'  
  
    def displayit(self):  
        print("The Dictionary from object fields belongs to the class Flowers :")  
  
  
# object animal of class Animals  
flower = Flowers()  
  
# calling displayit function  
flower.displayit()  
# calling the attribute __dict__ on flower  
# object and making it print it  
print(flower.__dict__)  

Output:

The Dictionary from object fields belongs to the class Flowers :
{'Rose': 'red', 'Lily': 'white', 'Lotus': 'pink'}

Now let's talk about vars() function in python.

The vars() method returns the __dict__ (dictionary mapping) attribute of the given object.

Syntax

vars(object)

vars() Parameter

The vars() method takes a single parameter:

  • object - can be a module, class, instance, or any object having the __dict__ attribute

vars() Return Value

The vars() method returns:

  • __dict__ attribute of the given object.
  • methods in the local scope when no arguments are passed
  • TypeError if the object passed doesn't have the __dict__ attribute

Example: Python vars()

# vars() with no argument
print (vars())

# returns __dict__  of a dictionary object
print(vars(dict))

Output:

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}

{'__repr__': <slot wrapper '__repr__' of 'dict' objects>, '__hash__': None, '__getattribute__': <slot wrapper '__getattribute__' of 'dict' objects> ….}

Example 2 : vars() with No __dict__ Attribute Argument

string = "Jones"

# vars() with a string
print(vars(string))

Output:

TypeError: vars() argument must have __dict__ attribute

In the above example, we have passed a string "Jones" to the vars() method.

Since a string doesn't have the __dict__ attribute, we get a TypeError.

Thanks for reading !!!

#python #python3 #naturallanguageprocessing #web-development #machine-learning

__dict__ attribute and vars() Function in Python
1.50 GEEK