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

C. Operator Overloading, Method Overloading, Method Overriding in Pythong Threads

The document discusses key concepts in Python programming, including method overriding, polymorphism, operator overloading, and thread management. It explains how subclasses can override superclass methods and the use of abstract classes and methods. Additionally, it covers the differences between overloading and overriding, as well as thread synchronization and potential deadlocks.

Uploaded by

tovilas
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)
11 views4 pages

C. Operator Overloading, Method Overloading, Method Overriding in Pythong Threads

The document discusses key concepts in Python programming, including method overriding, polymorphism, operator overloading, and thread management. It explains how subclasses can override superclass methods and the use of abstract classes and methods. Additionally, it covers the differences between overloading and overriding, as well as thread synchronization and potential deadlocks.

Uploaded by

tovilas
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/ 4

def speak(self):

Overriding Super Class Constructors and print("Cat meows")


Methods:
Subclass methods can override superclass methods animals = [Dog(), Cat()]
to provide specialized functionality. for animal in animals:
animal.speak() # Output: Dog barks \n Cat
Example: meows
class Animal:
def speak(self):
print("Animal speaks") Duck Typing:
In Python, the concept of Duck Typing refers to
class Dog(Animal): the idea that "if it looks like a duck and quacks like
def speak(self): # Overriding the superclass a duck, it must be a duck." Python doesn’t require
method explicit inheritance or interface implementation. If
print("Dog barks") an object has the methods and properties expected
by the code, it can be used, regardless of its class.
dog = Dog()
dog.speak() # Output: Dog barks Example:
class Duck:
def quack(self):
super() method: print("Quack!")
The super() function is used to call methods from
the superclass. It is often used to call the class Person:
constructor of the superclass. def quack(self):
print("I'm quacking like a duck!")
Example:
class A: def make_it_quack(duck):
def __init__(self): duck.quack()
print("Class A constructor")
make_it_quack(Duck()) # Output: Quack!
class B(A): make_it_quack(Person()) # Output: I'm quacking
def __init__(self): like a duck!
super().__init__() # Calling constructor of
class A Operator Overloading:
print("Class B constructor")
Operator overloading allows us to redefine the
b = B() # Output: Class A constructor \n Class B behavior of operators for custom objects.
constructor
Example:
Polymorphism: class Point:
def __init__(self, x, y):
Polymorphism means the ability to take many forms. It self.x = x
allows objects of different classes to be treated as self.y = y
objects of a common superclass. The most common use
of polymorphism is when a method in a superclass is def __add__(self, other):
overridden by a method in a subclass. return Point(self.x + other.x, self.y + other.y)
Example: p1 = Point(2, 3)
class Animal: p2 = Point(4, 5)
def speak(self): result = p1 + p2
print("Animal speaks") print(result.x, result.y) # Output: 6 8

class Dog(Animal):
def speak(self):
print("Dog barks")

class Cat(Animal):
Method Overloading: Method overloading is Example:
not natively supported in Python, but you can from abc import ABC, abstractmethod
achieve it by default arguments or variable-length
arguments. class Animal(ABC):
Example1: (using default arguments): @abstractmethod
class Calculator: def sound(self):
def add(self, a, b=0): pass
return a + b
class Dog(Animal):
calc = Calculator() def sound(self):
print(calc.add(5)) # Output: 5 print("Bark")
print(calc.add(5, 10)) # Output: 15
dog = Dog()
Example2 (method overloading using *args, args): dog.sound() # Output: Bark
class Calculator:
def add(self, *args):
return sum(args) Abstract Method: An abstract method is a
method that is declared in an abstract class and
must be implemented by any subclass of that class.
calc = Calculator()
print(calc.add(2, 3)) # 5 (Adding two Example:
numbers) class Shape(ABC):
print(calc.add(1, 2, 3, 4)) # 10 (Adding four @abstractmethod
numbers) def area(self):
pass
Note: The add method uses *args, which allows it
class Circle(Shape):
to accept a variable number of arguments
def __init__(self, radius):
self.radius = radius
Method Overriding: Method overriding is when
a subclass defines a method with the same name as
def area(self):
a method in the superclass.
return 3.14 * self.radius ** 2
Example:
circle = Circle(5)
class Animal:
print(circle.area()) # Output: 78.5
def speak(self):
print("Animal speaks")
Interfaces in Python (not supported in Python):
class Dog(Animal): Python does not have interfaces explicitly, but you
def speak(self): # Overriding speak method can create interfaces using abstract classes.
print("Dog barks")
Example:
dog = Dog() from abc import ABC, abstractmethod
dog.speak() # Output: Dog barks
class Movable(ABC):
2. Abstract Classes and Interfaces @abstractmethod
def move(self):
Abstract Class: An abstract class is a class that pass
cannot be instantiated on its own and is meant to be
subclassed. It often contains abstract methods that class Car(Movable):
must be implemented by the subclass. def move(self):
print("Car is moving")
Syntax:
from abc import ABC, abstractmethod car = Car()
car.move() # Output: Car is moving
class Animal(ABC):
@abstractmethod
def sound(self):
pass
3. Threads in Python Example:
import threading
Creating Threads in Python:
Threads are used to perform multiple operations lock = threading.Lock()
concurrently in Python. The threading module is
used to create threads. def task():
Syntax:
lock.acquire() # Lock acquired
print("Task is running")
import threading
lock.release() # Lock released
def task():
t = threading.Thread(target=task)
print("Task is running") t.start()
thread = threading.Thread(target=task) Deadlock in Threads:
thread.start()
Deadlock occurs when two or more threads are
Example:
blocked forever, each waiting for the other to
import threading release a resource.
def print_numbers(): Example:
for i in range(5): import threading
print(i)
t = threading.Thread(target=print_numbers) lock1 = threading.Lock()
t.start() lock2 = threading.Lock()
Single Tasking and Multitasking: def task1():
Single Tasking: Only one task is executed at a time
lock1.acquire()
Multitasking: Multiple tasks can be executed
concurrently using threads.
lock2.acquire()
print("Task 1 is running")
Example (Multitasking): lock2.release()
import threading lock1.release()
def task2():
def task1(): lock2.acquire()
print("Task 1") lock1.acquire()
def task2(): print("Task 2 is running")
print("Task 2") lock1.release()
lock2.release()
t1 = threading.Thread(target=task1)
t2 = threading.Thread(target=task2) t1 = threading.Thread(target=task1)
t1.start() t2 = threading.Thread(target=task2)
t2.start()
t1.start()
Thread Synchronization:
t2.start()
Thread synchronization is used to control the
access of shared resources by multiple threads. The The above code results in a deadlock.
Lock object is used to achieve synchronization.
Thread t1 acquired lock1 and attempted to
Thread synchronization in Python ensures that acquire lock2.Thread t2 acquired lock2 and
multiple threads can work together without
attempted to acquire lock1 .
interfering with each other, often by controlling
Since both threads are waiting for each other
access to shared resources.The Lock() method
to release the locks they need, they are stuck
provides a simple mechanism to prevent multiple
threads from accessing a shared resource
in an infinite wait state, leading to a deadlock.
simultaneously by acquiring and releasing the lock. This behavior can often hang indefinitely
without intervention.
Difference between overloading and overriding in Python:

Feature Overloading Overriding


Definition Defining multiple methods with the Redefining a method in a subclass that is
same name but different parameters in already defined in its parent class.
a class.
Parameters Methods have different parameter lists
The method in the subclass has the same
(number or types of parameters). name, parameters, and return type as in the
parent class.
Usage Used to perform different operations Used to provide specific implementation of
based on the parameter types or a method in a subclass.
counts.
Polymorphism Compile-time polymorphism Runtime polymorphism.
Type (simulated in Python).
Support in Not directly supported; simulated Fully supported in Python.
Python using default or variable-length
arguments.
Key Mechanism Differentiation based on parameter Overridden method in the subclass
count or types (achieved via *args or replaces the method from the parent class.
**kwargs).
Class Relation Works within the same class. Works across parent and child classes.
Example Class Example: class Parent:
def display(self, a=None): def display(self):
if a: print("Parent Display")
print(f"Value: {a}") class Child(Parent):
else: def display(self):
print("No Value") print("Child Display")
obj = Example() obj = Child()
obj.display() # No Value obj.display() # Child Display
obj.display(10) # Value: 10

You might also like