Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to organize code into reusable and modular components. It helps to model real-world scenarios and establish relationships between different entities in code.
Core Concepts of OOP
- Classes
and Objects
- Inheritance
- Encapsulation
- Polymorphism
- Abstraction
1. Classes and Objects
Class:
A class is a blueprint for creating objects. It defines properties
(attributes) and methods (behaviors).
# Defining a class
class Car:
# Class
attribute
wheels = 4
# Constructor
(initializer)
def __init__(self,
brand, color):
self.brand
= brand # Instance attribute
self.color
= color
# Method to
display car details
def display_info(self):
print(f"Brand:
{self.brand}, Color: {self.color}, Wheels: {Car.wheels}")
Object:
An object is an instance of a class.
# Creating objects
car1 = Car("Tesla", "Red")
car2 = Car("BMW", "Blue")
# Accessing methods and attributes
car1.display_info()
# Output: Brand: Tesla, Color: Red, Wheels: 4
car2.display_info()
# Output: Brand: BMW, Color: Blue, Wheels: 4
The 'self' Parameter
The self parameter is a reference to the current instance of a class. It is used to access variables and methods that belong to the class.
Why self is Important:
- Access Instance Variables: Allows each object to have unique attributes.
- Call Instance Methods: Helps in calling methods from within the class.
- Maintain Object Context: Differentiates between instance variables and local variables.
2. Inheritance
Inheritance allows a class (child class) to inherit attributes
and methods from another class (parent class), promoting code reuse.
# Parent class
class Vehicle:
def __init__(self,
name, max_speed):
self.name =
name
self.max_speed = max_speed
def display(self):
print(f"Vehicle:
{self.name}, Max Speed: {self.max_speed}")
# Child class (inherits from Vehicle)
class Car(Vehicle):
def __init__(self,
name, max_speed, brand):
super().__init__(name,
max_speed) # Call parent constructor
self.brand
= brand
def display(self):
super().display()
print(f"Brand:
{self.brand}")
# Example usage
car = Car("Sedan", 200, "Toyota")
car.display()
Types of Inheritance:
- Single
Inheritance: One parent, one child class.
- Multiple
Inheritance: One child class inherits from multiple parent classes.
class Class1:
pass
class Class2:
pass
class DerivedClass(Class1, Class2):
pass
- Multilevel
Inheritance: A child class is a parent of another class.
- Hierarchical
Inheritance: Multiple child classes inherit from one parent class.
- Hybrid Inheritance: Combination of multiple and multilevel inheritance.
3. Encapsulation
Encapsulation is wrapping data and methods into a single unit
(class) and controlling access using access modifiers.
- Public:
Accessible from anywhere (name).
- Protected:
Accessible from within the class and subclasses (_name).
- Private:
Accessible only within the class (__name).
class Account:
def __init__(self,
owner, balance):
self.owner
= owner # Public attribute
self._balance = balance #
Protected attribute
self.__pin
= "1234" # Private
attribute
def get_pin(self):
return
self.__pin
account = Account("John", 1000)
print(account.owner)
# Public: Access allowed
print(account._balance)
# Protected: Access allowed (not recommended)
print(account.get_pin())
# Private: Access via method
# print(account.__pin)
# Error: AttributeError
print(account._Account__pin) # Accessing private (not recommended)
4. Polymorphism
Polymorphism allows different classes to use the same
method name but perform different behaviors.
Method Overloading (Not Native in Python)
class MathOperations:
def add(self,
a=None, b=None, c=None):
if a is not
None and b is not None and c is not None:
return
a + b + c
elif a is not
None and b is not None:
return
a + b
else:
return
a
math = MathOperations()
print(math.add(2, 3)) # Output: 5
print(math.add(2, 3, 4)) # Output: 9
Method Overriding
class Animal:
def sound(self):
print("Some
sound")
class Dog(Animal):
def sound(self):
print("Bark")
class Cat(Animal):
def sound(self):
print("Meow")
# Polymorphism in action
for animal in (Dog(), Cat()):
animal.sound()
5. Abstraction
Abstraction hides complex implementation details and
shows only essential features. It is achieved using abstract classes and interfaces.
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
print("Bark")
class Cat(Animal):
def sound(self):
print("Meow")
# animal = Animal()
# Error: Can't instantiate abstract class
dog = Dog()
dog.sound() #
Output: Bark
Additional OOP Concepts in Python
1. Constructors (__init__):
The constructor is called automatically when an object is
created.
class Sample:
def __init__(self,
value):
self.value
= value
obj = Sample(10)
print(obj.value) #
Output: 10
2. Destructors (__del__):
The destructor is called when an object is deleted or goes
out of scope.
class Sample:
def __del__(self):
print("Destructor
called")
obj = Sample()
del obj # Output:
Destructor called
3. self Parameter:
- Refers
to the current instance of the class.
- Used
to access attributes and methods.
More details on Constructor
Benefits of OOP:
- Modularity:
Code is organized into self-contained objects.
- Reusability:
Through inheritance and polymorphism.
- Scalability:
Easily extend existing classes.
- Maintainability:
Encapsulation helps in managing complex codebases.
Use Cases of OOP:
- Game
Development: Using objects to represent characters, items, and world
elements.
- GUI
Development: Widgets and UI components are implemented as objects.
- Data
Modeling: Creating data structures using classes.
- Simulation
Systems: Modeling real-world entities and interactions.
Conclusion:
- OOP
is a powerful paradigm in Python, promoting clean code and logical
structure.
- It is widely used in software development, enabling robust and flexible applications.
No comments:
Post a Comment