Q:

What is __init__ in Python?

0

What is __init__ in Python?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer :

__init__  is a constructor of python classes and a reserved method. The __init__ method is called automatically whenever a new object is instantiated. This method allocates memory to the new object as soon as it is created. This method can also be used to initialize variables.
Here is an example of how to use it.
class Rectangle:
   def __init__(self, length, breadth, unit_cost=0):
       self.length = length
       self.breadth = breadth
       self.unit_cost = unit_cost
   def get_area(self):
       return self.length * self.breadth
   def calculate_cost(self):
       area = self.get_area()
       return area * self.unit_cost
# breadth = 10 units, length = 16 units, 1 sq unit cost = Rs 100
r = Rectangle(16, 10, 100)
print("Area of Rectangle: %s sq units" % (r.get_area()))
print("Cost of the Area: Rs= %d" % (r.calculate_cost()))

Output:

Area of Rectangle: 160 sq units
Cost of the Area: Rs= 16000

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Interview Questions and Answers

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
What is the difference between self and __init__ m... >>
<< How to call a function in python?...