- This is a function which we do not need to call.
- If we define this function in the class then it is the first function in the life of an object which is called.
- When we create an object of the class in which this function is defined then this function is called automatically for that object.
- Mainly this function is used to define instance members of the object.
- If you have knowledge of java or c++ language, then you can say that this function is just similar to constructor.
**One argument is necessary in __init__ function while we define it.
When an object call this function object itself is passed as a first argument.
class square:
def __init__(self,side):
self.side=side
def calarea(self):
x=self.side
print("The area of square is ",x*x)
s1=square(10)
s2=square(20)
s1.calarea()
Output:
The area of square is 100
The area of square is 400
Example2: Write an script to calculate the area of rectangle whose length and breadth are taken from the user in object oriented way.
class rect:
def __init__(self,l,b):
self.l=l
self.b=b
def calarea(self):
x=self.l
y=self.b
print("The area of rectangle is",x*y)
a,b=int(input("Enter length ")),int(input("Enter breadth "))
r1=rect(a,b)
r1.calarea()
Output:
Enter length 3
Enter breadth 4
The area of rectangle is 12