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.
object.__dict__
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'}
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'}
The vars()
method returns the __dict__
(dictionary mapping) attribute of the given object.
Syntax
vars(object)
The vars()
method takes a single parameter:
__dict__
attributeThe vars()
method returns:
__dict__
attribute of the given object.__dict__
attribute# 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> ….}
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