Programming with Python
Unit III
[Link]
Assistant Professor
Department of B Com(CA)
PSGR Krishnammal College for Women, Coimbatore
SYLLABUS-UNIT III
Object Oriented Programming: Classes and Objects –
Constructors – Destructors Getter and Setter Methods –
Encapsulations – Inheritance – Polymorphism – Abstract
Classes and Interfaces.
Constructors in Python
Recap of Classes & Objects
• Class → Blueprint for creating objects
• Object → Instance of a class
• Objects often need initial values when created
• Problem: Manual initialization is repetitive
• Solution: Use Constructor method
What is a Constructor?
• A special method in Python classes
• Automatically invoked when object is created
• Purpose: Initialize object attributes
• Similar to constructors in C++/Java
Constructor Syntax
• def __init__(self, parameters):
• [Link] = parameters
• `__init__` is a reserved method name
• `self` refers to current instance
• Called automatically
Simple Constructor Example
• class Student:
• def __init__(self, name):
• [Link] = name
• s1 = Student('Anita')
• print([Link]) → Anita
Why Constructors Are Important
• Avoid repetitive initialization
• Ensure consistency of objects
• Improve readability and maintainability
• Guarantee valid state at creation
Types of Constructors
• Default Constructor – no arguments
• Parameterized Constructor – accepts arguments
• Constructor with Default Parameters
Default Constructor Example
• class Demo:
• def __init__(self):
• print('Default Constructor called')
• obj = Demo()
Parameterized Constructor Example
• class Employee:
• def __init__(self, name, salary):
• [Link] = name; [Link] = salary
• e1 = Employee('Rahul', 45000)
• print([Link], [Link])
Constructor with Default Parameters
• class Car:
• def __init__(self, model='Unknown'):
• [Link] = model
• c1 = Car(); c2 = Car('Toyota')
• print([Link], [Link]) → Unknown Toyota
Constructor in Inheritance
• Parent constructor runs unless overridden
• Child constructor overrides parent constructor
• Use super() to call parent constructor
Inheritance Example
• class Person:
• def __init__(self, name): [Link] = name
• class Student(Person):
• def __init__(self, name, roll):
• super().__init__(name); [Link] = roll
• s = Student('Arun', 101) → Arun 101
Destructor vs Constructor
• Constructor (__init__) → Initialization
• Destructor (__del__) → Cleanup resources
• Called automatically by Python's memory
management
Common Errors & Best Practices
• Forgetting self as parameter → Error
• Mismatched parameter count
• Overriding parent constructor incorrectly
• Always use super() in inheritance
• Initialize all required attributes
Summary
• Constructors are special methods (__init__)
• Used to initialize object attributes
• Types: Default, Parameterized, Default
Arguments
• Inheritance with super()
• Destructor complements constructor
ASSESSMENT-QUIZ
• [Link]