Methods and Constructors in Python

What is a Constructor?

  • Special type of method with the same name as that of the class name
  • Used to assign the value to the variable during the object creation
  • __init__() keyword is used define the constructor in Python

Type of Constructors

  • Default Constructor
    • Takes no parameter
    • Defined by the class or by the user
  • Parameterized Constructor
    • Takes Parameter
    • Defined by the user

Example for Default Constructor

#class declaration
class Laptop:

#Default constructor
def __init__(self):

self.brand=”HP”
self.color=”Black”
self.price=50000.00

# method declaration
def showLaptopInfo(self):

print(“Brand :”, self.brand)
print(“Color :”, self.color)
print(“Price :”, self.price)

#object creation
objLp=Laptop() # calling th default constructor

# calling the methods
print(“Example : Default Constructor”)
print(“Laptop Details :”)
objLp.showLaptopInfo()

Example for Parameterized Constructor

#class declaration
class Laptop:

#parametrize constructor
def __init__(self, brand, color, price):

self.brand=brand
self.color=color
self.price=price

# Method declaration
def showLaptopInfo(self):

print(“Brand :”, self.brand)
print(“Color :”, self.color)
print(“Price :”, self.price)

#object creation
objLp=Laptop(“HP”, “Black”, 45000.00)
objLp1=Laptop(“Dell”, “Grey”, 35000.00)

# calling the methods
print(“Example : parameterized constructor”)
print(“Laptop Details :”)
objLp.showLaptopInfo()
objLp1.showLaptopInfo()

Difference Between Methods and Constructors

Method Constructor
1. Name: Each method in the class will have different name 1.Name: Constructor will have the same name as that of the class name.
__init__() keyword is used to define the constructor in python
2. Task

a. To Assign the Value
b. To Print the Output
c. To Perform Calculation and Comparison

2. Task
a. To Assign the Value
3. Takes Parameter [Optional] 3. Takes Parameter [Optional]
4. Returns value after Calculation or Comparison 4. No Return Type
5. Explicitly called using Object 5. Implicitly Called.

 

Win Corporate Training
website: http://www.wincorptrg.com
View My Profile

Advertisements