0% found this document useful (0 votes)
7 views4 pages

Python OOP Concepts: Classes & Inheritance

The document outlines an academic assignment for students at Mahatma Gandhi Mission’s College of Engineering and Technology, focusing on Object Oriented Programming in Python. It includes three programming tasks: understanding classes and static methods, constructors, and inheritance with polymorphism. Each task is accompanied by source code examples demonstrating the concepts.

Uploaded by

shubham
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views4 pages

Python OOP Concepts: Classes & Inheritance

The document outlines an academic assignment for students at Mahatma Gandhi Mission’s College of Engineering and Technology, focusing on Object Oriented Programming in Python. It includes three programming tasks: understanding classes and static methods, constructors, and inheritance with polymorphism. Each task is accompanied by source code examples demonstrating the concepts.

Uploaded by

shubham
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Mahatma Gandhi Mission’s College of Engineering and Technology

Department of Computer Science and Engineering (AIML & DS)

Academic Year 2024-2025(Even Sem)

Name Of Student Mohit Joshi

Roll No 20
DOP DOS Marks/Grade Signature

Experment No:-3

Aim: Write python programs to understand concepts of Object Oriented


Programming.

Objective:∙ Object Oriented Programming concepts in python.

Outcome: Students will be able to understand concepts of Object


Oriented Programming in python.

i) WAP to understand Classes, objects, Static method and inner class.

Source Code:

class OuterClass:
@staticmethod
def static_method():
return "This is a static method in the OuterClass."

class InnerClass:
def __init__(self, name):
[Link] = name
def display(self):
return f"Hello from InnerClass, {[Link]}!"

outer_object = OuterClass()
print(outer_object.static_method())

inner_object = [Link]("PYTHON")
print(inner_object.display())

Input and Output:

ii) WAP to understand Constructors.

Source Code:

class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age

def display_info(self):
return f"Name: {[Link]}, Age: {[Link]}"

person1 = Person("David", 30)


person2 = Person("Jhon", 25)
person3 = Person("Tom", 15)
print(person1.display_info())
print(person2.display_info())
print(person3.display_info())

Input and Output:

iii) WAP to understand Inheritance and Polymorphism with Method


overloading and Method Overriding.
Source Code:
class Animal:
def sound(self):
return "Some sound"

class Dog(Animal):
def sound(self):
return "Bark"

class Cat(Animal):
def sound(self):
return "Meow"

class Bird(Animal):
def sound(self):
return "Chirp"

class Calculator:
def add(self, a, b):
return a + b

def add_three(self, a, b, c):


return a + b + c

def demonstrate_inheritance_and_polymorphism():
animals = [Dog(), Cat(), Bird()]
for animal in animals:
print(f"{animal.__class__.__name__} makes sound:
{[Link]()}")

def demonstrate_method_overloading():
calc = Calculator()
print("Addition of two numbers:", [Link](10, 40))
print("Addition of three numbers:", calc.add_three(10, 20, 50))
demonstrate_inheritance_and_polymorphism()
demonstrate_method_overloading()
Input and Output:

Common questions

Powered by AI

Method overriding in Python occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. This allows subclass instances to call the overridden method, thus invoking the subclass's version rather than the parent's. In the provided example, the method `sound` is overridden by the `Dog`, `Cat`, and `Bird` classes, allowing them to return different strings ('Bark', 'Meow', 'Chirp', respectively) when `sound` is called. This demonstrates the flexibility of Python’s OOP capabilities in allowing detailed customization and extension of base class functionalities .

Python implements polymorphism through method overriding by allowing a subclass to define a method with the same name as a method in its superclass. This enables the subclass to provide a specific implementation that will be called on objects of the subclass type. In the example provided, the `Dog`, `Cat`, and `Bird` classes override the `sound` method of the `Animal` class to return unique sound strings. This polymorphic behavior allows the same interface to be used interactively with different underlying forms, offering flexibility and the ability to easily extend code with new behaviors through subclassing .

Teaching object-oriented programming (OOP) through practical coding exercises is significant because it bridges theoretical concepts with real-world application, enhancing comprehension and retention among students. Exercises like the given examples enable learners to actively engage with core OOP principles—classes, inheritance, polymorphism—by experimenting and observing their implementation directly, which reinforces understanding. This experiential learning approach fosters problem-solving skills, as students iteratively refine code to meet objectives, promoting deeper insights into how object-oriented design patterns facilitate modularity, encapsulation, and code reuse .

Static methods in object-oriented design, particularly in Python, offer the advantage of being callable without instantiating an object, thus preserving memory and simplifying scenarios where a function pertains to general utility across instances. They help in organizing code within the class namespace, reducing the global scope's pollution. However, static methods cannot access any instance data or methods, which can be limiting in designs heavily reliant on state interaction. In the provided example, the static method `static_method()` in `OuterClass` serves as a general utility function but cannot interact with instance-level data, highlighting both its potential and limitation in encapsulation and accessibility .

Python does not directly support constructor overloading as seen in languages like Java or C++, where multiple constructors can coexist with different parameters. Instead, Python uses a single constructor `__init__()`, and any overloading-like behavior must be simulated using default parameters or conditional logic based on the type or number of inputs. This contrasts with method overloading, where Python achieves similar functionality by providing separate methods with different parameter counts or using variable-length arguments and keyword arguments to accommodate variations in input .

Method overriding involves redefining a method in a subclass that has the same name and parameters as a method in its parent class, allowing for specific behavior in the subclass instance. Method overloading, in contrast, relates to defining multiple methods with the same name in a single class, but differing in parameter signatures, which Python handles differently compared to languages like Java. Python implements overloading through default arguments and *args or **kwargs, as seen in the `Calculator` class's `add` methods, which differ by the number of arguments they accept. This showcases the flexibility in function signatures and behavior based on passed parameters .

Static methods in Python are defined using the @staticmethod decorator and can be called on a class without an instance. They do not have access to instance variables or instance methods, so they function similarly to regular functions defined within a module. Inner classes, on the other hand, are defined within another class and can access its containing class's static and class-level data directly if needed, but typically focus on encapsulating related behavior and data structures. In the provided example, the static method `static_method()` returns a string that signifies its role, and the inner class `InnerClass` maintains and displays its own data independent of the outer class. Together, they illustrate how different components of a class can interact or remain independent as needed .

Inner classes in Python contribute to encapsulation by grouping related functionality and data within a containing class, thus promoting a higher level of organization and modularization. They can access the attributes and methods of the enclosing class directly, enabling a more structured and restricted access to parts of the code that should not be exposed globally. In the example, `InnerClass` encapsulates its own behavior and attributes (`name` and `display` method) under `OuterClass`, reducing the namespace pollution and isolating its implementation details. This design provides a cleaner and more maintainable codebase .

In Python, method overloading can be effectively simulated using default arguments, *args, **kwargs, or function decorators like `functools.singledispatch` which allow for a single function to behave differently based on input data types or number of arguments. This approach mimics traditional overloading in other languages by customizing function behavior internally rather than defining methods with unique signatures. For instance, in the `Calculator` class, method `add` handles two arguments while `add_three` processes three, showcasing how logic is varied by adding different method implementations. This methodology balances Python's flexibility with the need for overload-like behavior .

Python's inheritance model supports code reuse by allowing subclasses to inherit attributes and methods from a parent class, reducing the need to reimplement common logic. This model can be observed in the example where `Dog`, `Cat`, and `Bird` classes inherit from `Animal`, using the `sound` method offered by the superclass as a base for their specific implementations. This not only streamlines code management and reduces redundancy but also facilitates the maintenance and scalability of code, as shared functionality can be altered in one place—within the parent class—affecting all child classes without additional rework .

You might also like