Get A Dictionary From An Objects Fields
Get A Dictionary From An Objects Fields
In this article, we will discuss how to get a dictionary from object’s field i.e. how
to get the class members in the form of a dictionary. There are two approaches to
solve the above problem:
By using the __dict__ attribute on an object of a class and attaining the dictionary.
All objects in Python have an attribute __dict__, which is a dictionary object
containing all attributes defined for that object itself. The mapping of attributes
with its values is done to generate a dictionary.
By calling the in-built vars method, which is used to return __dict__ attribute of a
module, class, class instance, or an object.
#Method 1: To generate a dictionary from an arbitrary object using
__dict__attribute:
# class Animals is declared
class Animals:
# constructor
def __init__(self):
def printit(self):
print("Dictionary from the object fields\
belonging to the class Animals:")
# object animal of class Animals
animal = Animals()
# class A is declared
class A:
# constructor
def __init__(self):
# keys are initialized with
# their respective values
self.A = 1
self.B = 2
self.C = 3
self.D = 4
class Mother:
mothername = ""
def mother(self):
print(self.mothername)
class Father:
fathername = ""
def father(self):
print(self.fathername)
class Son(Mother, Father):
def parents(self):
print("Father :", self.fathername)
print("Mother :", self.mothername)
s1 = Son()
s1.fathername = "RAM"
s1.mothername = "SITA"
s1.parents()
Multilevel Inheritance
In multilevel inheritance, features of the base class and the derived class are further
inherited into the new derived class. This is similar to a relationship representing a
child and grandfather.
# Base class
class Grandfather:
def __init__(self, grandfathername):
self.grandfathername = grandfathername
# Intermediate class
class Father(Grandfather):
def __init__(self, fathername, grandfathername):
self.fathername = fathername
class First:
def __init__(self):
self.x = 20
self.y = 10
class Second(First):
def findsum(self):
self.z = self.x + self.y
print("Sum is:", self.z)
class Third(First):
def findsub(self):
self.z = self.x - self.y
print("Subtraction is:", self.z)
obj1 = Second()
obj1.findsum()
Hybrid Inheritance:
• Inheritance consisting of multiple types of inheritance is called hybrid
inheritance.