Python Program to Form a Dictionary from an Object of a Class


When it is required to form a dictionary with the help of an object and class, a class is defined. An ‘init’ function is defined, that assigns values to variables. An instance of the class is created, and the init function is called.

Example

Below is a demonstration for the same −

 Live Demo

class base_class(object):
   def __init__(self):
      self.A = 32
      self.B = 60
my_instance = base_class()
print("An instance of the class has been created")
print(my_instance.__dict__)

Output

An instance of the class has been created
{'A': 32, 'B': 60}

Explanation

  • A ‘base_class’ is defined, and an object is passed to it.
  • An ‘init’ method is defined, and it assigns values to variables.
  • An instance of the method is created.
  • The method is called using the obect created, using ‘.’ operator

Updated on: 12-Mar-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements