Constructor:
A constructor is a unique function that gets called automatically when an object is created of a class.
--> It is used to initialize objects when they are created.
--> The constructor method is named __init__()
self keyword:
--> It is Used to denote current object
Example:1
class Employee:
def __init__(self, name, qual,department, year):
self.empName = name
self.dept = department
self.joining_year = year
self.qual = qual
def work(self):
print("Working", self.empName, self.dept, self.joining_year)
emp1 = Employee("guru", "B.Com", "Development", 2025)
emp2 = Employee("pritha", "M.E.,", "Design", 2025)
emp1.work()
Output:
Working guru Development 2025
Example:2
class Employee:
salary = 25000
def __init__(self, name, qual,department, year):
self.empName = name
self.dept = department
self.joining_year = year
self.qual = qual
def work(self):
print("Working", self.empName, self.dept, self.joining_year)
print(self.salary)
emp1 = Employee("guru", "B.Com", "Development", 2025)
emp2 = Employee("pritha", "M.E.,", "Design", 2025)
emp1.work()
Output:
Working guru Development 2025
25000
__dict__
: __dict__
is a special attribute of objects that stores all instance attributes as a dictionary.
Example:
class Employee:
salary = 25000
def __init__(self, name, qual,department, year):
self.empName = name
self.dept = department
self.joining_year = year
self.qual = qual
def work(self):
print("Working", self.empName, self.dept, self.joining_year)
print(self.salary)
emp1 = Employee("guru", "B.Com", "Development", 2025)
emp2 = Employee("pritha", "M.E.,", "Design", 2025)
print(Employee.__dict__)
print(emp1.__dict__)
print(emp2.__dict__)
Output:
{'__module__': '__main__', 'salary': 25000, '__init__': <function Employee.__init__ at 0x7265db745300>, 'work': <function Employee.work at 0x7265db7acea0>, '__dict__': <attribute '__dict__' of 'Employee' objects>, '__weakref__': <attribute '__weakref__' of 'Employee' objects>, '__doc__': None}
{'empName': 'guru', 'dept': 'Development', 'joining_year': 2025, 'qual': 'B.Com'}
{'empName': 'pritha', 'dept': 'Design', 'joining_year': 2025, 'qual': 'M.E.,'}
Class Method with Decorator
A class method is a method that operates on the class itself rather than an instance. It is defined using the @classmethod decorator and takes cls (class reference) as its first parameter.
Example:
class Employee:
salary = 25000
def __init__(self, name, qual,department, year):
self.empName = name
self.dept = department
self.joining_year = year
self.qual = qual
@classmethod
def credit_salary(cls):
print("Credit salary on last day of every month")
def work(self):
print("Working", self.empName, self.dept, self.joining_year)
print(self.salary)
emp1 = Employee("guru", "B.Com", "Development", 2025)
emp2 = Employee("pritha", "M.E.,", "Design", 2025)
Employee.credit_salary()
Output:
Credit salary on last day of every month
Nested class:
A nested class (inner class) is a class defined inside another class.
Example:1(calling inner class using an Instance of the Outer Class)
class College:
def init(self):
print("College Constructor")
class Dept:
def init(self):
print("Dept Constructor")
def work(self):
print("Working")
principal = College()
hod = principal.Dept()
hod.work()
Example:2(calling inner class using the Outer Class Name Directly)
class College:
def __init__(self):
print("College Constructor")
class Dept:
def __init__(self):
print("Dept Constructor")
def work(self):
print("Working")
hod = College().Dept()
hod.work()
Output:(Same output for both examples)
College Constructor
Dept Constructor
Working
Constructor overloading:
--> Constructor overloading refers to defining multiple constructors with different sets of parameters in a class.
--> Python does not support multiple constructors (init methods)
--> Python achieves method overloading through default parameter values and variable-length argument(*args, or **kwargs) lists.
Example:
class SuperMarket:
def __init__(self,product_name, price, *discount):
self.product_name = product_name
self.price = price
self.discount = discount
def buy(self):
print(self.product_name, self.price, self.discount)class Shapes:
def find_area(self, side1, side2):
print(side1 * side2)
class Square(Shapes):
pass
s = Square()
s.find_area(5,5)
class Rectangle(Shapes):
pass
r = Rectangle()
r.find_area(10,8)
product1 = SuperMarket("soap", 50, 10)
product2 = SuperMarket("Brush", 60,20)
product1.buy()
product2.buy()
product3 = SuperMarket("Rice", 60)
product3.buy()
Output:
soap 50 (10,)
Brush 60 (20,)
Rice 60 ()
Inheritance
--> Inheritance allows us to define a class that inherits all the methods and properties from another class.
--> Parent class is the class being inherited from, also called base class.
--> Child class is the class that inherits from another class, also called derived class.
Types of Inheritance in Python
Python supports the following types of inheritance:
- Single Inheritance : A child class inherits from a single parent class.
- Multiple Inheritance : A child class inherits from multiple parent classes.
- Multilevel Inheritance : A child class inherits from a parent class, which itself inherits from another parent class.
- Hierarchical Inheritance : Multiple child classes inherit from the same parent class.
- Hybrid Inheritance : A combination of multiple inheritance types.
Example:
class Shapes:
def find_area(self, side1, side2):
print(side1 * side2)
class Square(Shapes):
pass
s = Square()
s.find_area(5,5)
class Rectangle(Shapes):
pass
r = Rectangle()
r.find_area(10,8)
Output:
25
80
Method Overriding(Runtime Polymorphism)
--> Method overriding occurs when a child class provides a specific implementation of a method that is already defined in its parent class.
--> The overridden method in the child class must have the same name and parameters as the method in the parent class.
Method Resolution Order(MRO)
Example: (multiple inheritance)
class Father:
def work(self):
print("Mechanical Engineer")
class Mother:
def work(self):
print("Software Engineer")
class Child(Mother, Father):
def work(self):
print("Business person")
child = Child()
child.work()
Output:
Business person
--> Child class derives from Mother and Father.
--> Python first checks Child.
--> If the method isn’t found, it checks Mother (first listed parent).
--> If still not found, it checks Father.
If none of the parent classes have the method, it checks object (the base class for all Python classes).
Operator Overloading
Operator overloading allows us to redefine the behavior of operators (+, -, *, etc.) for user-defined objects.
print(100+200)
print("Hi"+"Hello")
print(100*3)
print("Hi"*3)
Output:
300
HiHello
300
HiHiHi
--> operator + is used to add two integers as well as join two strings and merge two lists.
--> It is achievable because ‘+’ operator is overloaded by int class and str class.
Examples:
class Book:
def __init__(self, pages):
self.pages = pages
def __add__(self, second):
print(self.pages, second.pages)
return self.pages + second.pages
book1 = Book(300)
book2 = Book(200)
print(book1 + book2)
Output:
300 200
500
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def __mul__(self,other):
return self.salary * other.days
class TimeSheet:
def __init__(self, name, days):
self.name = name
self.days = days
emp1 = Employee("Guru", 1000)
timesheet1 = TimeSheet("Guru", 25)
print("Monthly salary:",emp1 * timesheet1)
Output:
Monthly salary: 25000
Top comments (0)