DEV Community

Guru prasanna
Guru prasanna

Posted on

Python Day - 34 Constructor, Inheritance, Overloading

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()
Enter fullscreen mode Exit fullscreen mode

Output:

Working guru Development 2025
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

Output:

Working guru Development 2025
25000
Enter fullscreen mode Exit fullscreen mode

__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__)
Enter fullscreen mode Exit fullscreen mode

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.,'}
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

Output:(Same output for both examples)

College Constructor
Dept Constructor
Working
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

Output:

soap 50 (10,)
Brush 60 (20,)
Rice 60 ()
Enter fullscreen mode Exit fullscreen mode

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.

Image description

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)
Enter fullscreen mode Exit fullscreen mode

Output:

25
80
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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).

Image description

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)
Enter fullscreen mode Exit fullscreen mode

Output:

300
HiHello
300
HiHiHi
Enter fullscreen mode Exit fullscreen mode

--> 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.

Image description

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)
Enter fullscreen mode Exit fullscreen mode

Output:

300 200
500
Enter fullscreen mode Exit fullscreen mode
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)
Enter fullscreen mode Exit fullscreen mode

Output:

Monthly salary: 25000

Top comments (0)