new_user
0
Q:

init function in python

The __init__ function serves two main purposes. 
The first is its used as a tool to pass 
arguments inside of it but the difference is you can spread those
arguments to other functions locaed in the same class. 
To do this you would place the word (self.) keyword in another functions 
followed by the arguments name. This allows the argument to be spread 
down to that function. 
The second purpose is it allows you to pass arguments to a 
class when calling the class. Without this function inside the class
when you call the class no arguments would be able to go inside getting
nothing in return.
6
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 = 120 units, length = 160 units, 1 sq unit cost = Rs 2000
r = Rectangle(160, 120, 2000)
print("Area of Rectangle: %s sq units" % (r.get_area()))
1
class Employee():
    no_of_leaves = 8

    def __init__(self, aname, asalary, arole):
        self.name = aname
        self.salary = asalary
        self.role = arole

    def printdetail(self):
        return f"Name is {self.name}. His salary is {self.salary}." \
               f"and his role is {self.role}"
0

New to Communities?

Join the community