[go: up one dir, main page]

0% found this document useful (0 votes)
8 views5 pages

Polymorphism

Polymorphism is a key concept in Object-Oriented Programming that allows objects of different classes to be treated as instances of a common superclass, enabling methods to behave differently based on the object type. It includes compile-time polymorphism (method and operator overloading) and run-time polymorphism (method overriding). The document also covers data structures in Python, including lists, tuples, and dictionaries, highlighting their characteristics and differences.

Uploaded by

dassonai897
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)
8 views5 pages

Polymorphism

Polymorphism is a key concept in Object-Oriented Programming that allows objects of different classes to be treated as instances of a common superclass, enabling methods to behave differently based on the object type. It includes compile-time polymorphism (method and operator overloading) and run-time polymorphism (method overriding). The document also covers data structures in Python, including lists, tuples, and dictionaries, highlighting their characteristics and differences.

Uploaded by

dassonai897
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
You are on page 1/ 5

Polymorphism

Polymorphism is a fundamental concept in programming, especially in Object-Oriented


Programming (OOP). The term "polymorphism" comes from the Greek words "poly" (many)
and "morph" (form), meaning many forms. It allows objects of different classes to be treated
as objects of a common superclass, enabling a single interface to represent different data
types or classes.

Key Points about Polymorphism

1. Definition: Polymorphism allows methods or operations to behave differently based


on the object or data type they are acting on.
2. Types of Polymorphism:
o Compile-time Polymorphism (Static): Achieved through method
overloading or operator overloading.
o Run-time Polymorphism (Dynamic): Achieved through method overriding
in inheritance.

Types of Polymorphism in Detail

1. Compile-time Polymorphism (Static Polymorphism)

This happens when a function or operator behaves differently depending on the input
provided during compilation.

• Method Overloading: Defining multiple methods with the same name but different
parameters.
• class Calculator:
• def add(self, a, b):
• return a + b

• def add(self, a, b, c): # Overloading the add method
• return a + b + c

• calc = Calculator()
• print(calc.add(1, 2, 3)) # Output: 6
• Operator Overloading: Giving additional meaning to standard operators.
• class Point:
• def __init__(self, x, y):
• self.x = x
• self.y = y

• def __add__(self, other):
• return Point(self.x + other.x, self.y + other.y)

• p1 = Point(1, 2)
• p2 = Point(3, 4)
• result = p1 + p2
• print(result.x, result.y) # Output: 4, 6

2. Run-time Polymorphism (Dynamic Polymorphism)

This occurs when a subclass provides a specific implementation of a method that is already
defined in its parent class. It uses method overriding.

• Method Overriding: A child class redefines a method from its parent class.
• class Animal:
• def sound(self):
• print("Animal makes a sound")

• class Dog(Animal):
• def sound(self): # Overriding the sound method
• print("Dog barks")

• class Cat(Animal):
• def sound(self): # Overriding the sound method
• print("Cat meows")

• def make_sound(animal):
• animal.sound()

• dog = Dog()
• cat = Cat()
• make_sound(dog) # Output: Dog barks
• make_sound(cat) # Output: Cat meows

Advantages of Polymorphism

1. Code Reusability: Reduces duplication by enabling the same interface for different
implementations.
2. Flexibility: Allows methods to work with objects of various types.
3. Extensibility: Makes it easier to add new functionality without altering existing code.

Real-world Analogy

Consider a "remote control" (interface). It can work with multiple devices like a TV, AC, or
music system. The remote's behavior changes depending on the device it is connected to, but
the same interface (buttons) is used.

Polymorphism enables writing cleaner, more maintainable, and extendable code by


decoupling behavior from implementation.
Here’s a simple and detailed explanation of list, tuple, and dictionary in Python:

1. List

A list is a collection of items that is:

• Ordered: The items have a defined sequence, and you can access them using an
index (starting from 0).
• Mutable: You can change, add, or remove items after the list is created.
• Allows duplicates: A list can have multiple items with the same value.

Syntax:

my_list = [1, 2, 3, 4] # A list of integers


my_list2 = ["apple", "banana", "cherry"] # A list of strings

Key Features:

• Use square brackets [ ].


• Items can be of any data type (int, float, string, or even another list).
• Allows item modification.

Example:

fruits = ["apple", "banana", "cherry"]


print(fruits[1]) # Access the second item: "banana"
fruits.append("orange") # Add "orange" to the list
fruits[0] = "grape" # Change "apple" to "grape"
print(fruits) # Output: ["grape", "banana", "cherry", "orange"]

2. Tuple

A tuple is similar to a list but with some differences:

• Ordered: Like a list, the items have a defined order.


• Immutable: Once a tuple is created, its contents cannot be changed.
• Allows duplicates: Like a list, it can have repeated values.

Syntax:

my_tuple = (1, 2, 3, 4) # A tuple of integers


my_tuple2 = ("apple", "banana", "cherry") # A tuple of strings

Key Features:

• Use parentheses ( ).
• Tuples are faster than lists because they are immutable.
• Useful for fixed collections of items.
Example:

coordinates = (10, 20)


print(coordinates[0]) # Access the first item: 10
# coordinates[1] = 30 # Error: Tuples cannot be modified

3. Dictionary

A dictionary is a collection of key-value pairs:

• Unordered (Python < 3.7), Ordered (Python ≥ 3.7): The order of items is preserved
in Python 3.7 and later.
• Mutable: You can change, add, or remove items.
• No duplicate keys: Each key must be unique, but values can repeat.

Syntax:

my_dict = {"key1": "value1", "key2": "value2"}

Key Features:

• Use curly braces { }.


• Access values by their keys (not index).
• Keys must be immutable (strings, numbers, or tuples), while values can be any type.

Example:

student = {"name": "John", "age": 21, "grade": "A"}


print(student["name"]) # Access value for key "name": "John"
student["age"] = 22 # Change the value of "age"
student["major"] = "Computer Science" # Add a new key-value pair
print(student) # Output: {'name': 'John', 'age': 22, 'grade': 'A',
'major': 'Computer Science'}

Comparison Table

Feature List Tuple Dictionary


Ordered ✅ Yes ✅ Yes ✅ Yes (Python ≥ 3.7)
Mutable ✅ Yes ❌ No ✅ Yes
Allows ❌ No (Keys) / ✅ Yes
✅ Yes ✅ Yes
Duplicates (Values)
Syntax [ ] ( ) {key: value}
Store a collection of items Fixed collection of Store data as key-value
Use Case
that can change items pairs

Quick Analogy:
• List: A shopping list — you can add, remove, or change items.
• Tuple: A person's date of birth — fixed and unchangeable.
• Dictionary: A contact book — you use a name (key) to find a phone number (value).

Apologies for the misunderstanding earlier! Here's a corrected table without examples as
points:

Feature break continue


Used to terminate the loop
Purpose Used to skip the rest of the current iteration.
entirely.
Stops further iterations of the Skips the remaining code in the current
Effect
loop. iteration and moves to the next iteration.
Control Moves execution to the first Transfers control back to the loop for the next
Flow statement after the loop. iteration.
Affects the entire loop, not just
Scope Affects only the current iteration.
a specific iteration.
Common Exiting loops early when a Ignoring specific iterations while continuing
Usage condition is met. the loop.

This table provides clear and distinct points for a 5-mark answer. Let me know if you’d like
further refinement!

Here’s a concise table for a 5-mark question on the difference between global and local
variables:

Aspect Global Variable Local Variable


Definition Declared outside any function. Declared within a specific function.
Accessible only within the
Scope Accessible throughout the program.
function/block.
Exists only during function
Persistence Exists for the program's lifetime.
execution.
Requires global keyword to modify
Modification Directly modifiable within its scope.
inside a function.
Used for values shared across Used for temporary operations
Use Case
functions. within a function.

Key Point: Global variables are used program-wide, while local variables are confined to
specific functions.

You might also like