1The __init__ function serves two main purposes.
2The first is its used as a tool to pass
3arguments inside of it but the difference is you can spread those
4arguments to other functions located in the same class.
5To do this you would place the word (self.) keyword in another function
6followed by the arguments name. This allows the argument to be spread
7down to that function.
8The second purpose is it allows you to pass arguments to a
9class when calling the class. Without this function inside the class
10when you call the class no arguments would be able to go inside getting
11nothing in return.
1class Rectangle:
2 def __init__(self, length, breadth, unit_cost=0):
3 self.length = length
4 self.breadth = breadth
5 self.unit_cost = unit_cost
6 def get_area(self):
7 return self.length * self.breadth
8 def calculate_cost(self):
9 area = self.get_area()
10 return area * self.unit_cost
11# breadth = 120 units, length = 160 units, 1 sq unit cost = Rs 2000
12r = Rectangle(160, 120, 2000)
13print("Area of Rectangle: %s sq units" % (r.get_area()))
1class Employee():
2 no_of_leaves = 8
3
4 def __init__(self, aname, asalary, arole):
5 self.name = aname
6 self.salary = asalary
7 self.role = arole
8
9 def printdetail(self):
10 return f"Name is {self.name}. His salary is {self.salary}." \
11 f"and his role is {self.role}"