1class Computer:
2 def __init__(self):
3 self.name= ("Pankaj")
4 self.age= 28
5c1=Computer()
6c2=Computer()
7c1.name= "Garg"
8print(c1.name)
9print(c2.name)
10
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.
1# If you are familiar with C++ or Java think of the __init__ method as a constructor.
2# It is the method that is being called when the class is called.In the following
3# example we will see how we can call the __init__ method
4
5my_variable = MyClass()
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}"