Object-Oriented Programming (OOP) is a programming paradigm based on the concept of objects, which are instances of classes. Python is an object-oriented programming language, and it supports OOP features like Encapsulation, Abstraction, Inheritance, and Polymorphism. Here’s an overview of these key OOP concepts in Python:
1. Class and Object
- Class: A class is a blueprint for creating objects. It defines a set of attributes and methods that an object of this class can have.
class Car: def __init__(self, make, model): self.make = make self.model = model def display(self): print(f"Car Make: {self.make}, Model: {self.model}") # Creating an object of the class my_car = Car("Toyota", "Camry") my_car.display() # Output: Car Make: Toyota, Model: Camry
- Object: An object is an instance of a class. It is created by calling the class, and it can access the methods and attributes of the class.
2. Encapsulation
Encapsulation refers to bundling the data (attributes) and methods that operate on the data within a single unit (class). It also hides the internal state of an object from the outside world, exposing only necessary information.
- Private attributes: In Python, attributes can be made private by prefixing them with double underscores (
__
). These cannot be accessed directly from outside the class.class Account: def __init__(self, balance): self.__balance = balance def deposit(self, amount): self.__balance += amount def get_balance(self): return self.__balance account = Account(1000) print(account.get_balance()) # Accessing through the method account.__balance = 5000 # This will not change the private balance attribute print(account.get_balance()) # Output will still be 1000
Here, the
__balance
attribute is encapsulated, and its access is controlled through methods likedeposit()
andget_balance()
.
3. Abstraction
Abstraction means hiding the implementation details and showing only the essential features of the object. In Python, this can be achieved by creating abstract classes and abstract methods.
- Abstract Class: An abstract class cannot be instantiated and is meant to be subclassed. It can contain abstract methods that must be implemented by subclasses.
from abc import ABC, abstractmethod class Animal(ABC): @abstractmethod def make_sound(self): pass class Dog(Animal): def make_sound(self): print("Woof!") dog = Dog() dog.make_sound() # Output: Woof!
The
make_sound
method is abstract in theAnimal
class, and must be implemented in theDog
class.
4. Inheritance
Inheritance allows a class (child class) to inherit attributes and methods from another class (parent class). This helps in code reusability and establishing relationships between classes.
- Single Inheritance: Inheriting from a single parent class.
class Animal: def speak(self): print("Animal is making a sound") class Dog(Animal): def speak(self): print("Dog barks") dog = Dog() dog.speak() # Output: Dog barks
- Multiple Inheritance: Inheriting from more than one parent class.
class Flyable: def fly(self): print("I can fly") class Animal: def move(self): print("I can move") class Bird(Animal, Flyable): def speak(self): print("Bird chirps") bird = Bird() bird.fly() # Output: I can fly bird.move() # Output: I can move bird.speak() # Output: Bird chirps
5. Polymorphism
Polymorphism allows objects of different classes to be treated as objects of a common base class. It also allows methods to have the same name but behave differently depending on the object calling it.
- Method Overloading: In Python, method overloading is not supported directly like other languages, but you can achieve it by using default arguments or variable-length arguments.
class Calculator: def add(self, a, b=0): return a + b calc = Calculator() print(calc.add(5)) # Output: 5 print(calc.add(5, 3)) # Output: 8
- Method Overriding: Method overriding is when a child class provides its own version of a method that is already defined in its parent class.
class Animal: def sound(self): print("Animal makes a sound") class Dog(Animal): def sound(self): print("Dog barks") dog = Dog() dog.sound() # Output: Dog barks
6. Constructor and Destructor
- Constructor (
__init__
): The constructor is a special method in Python, called when an object is created, to initialize the object’s attributes.class Person: def __init__(self, name, age): self.name = name self.age = age def display(self): print(f"Name: {self.name}, Age: {self.age}") person = Person("Alice", 30) person.display() # Output: Name: Alice, Age: 30
- Destructor (
__del__
): The destructor is a method that is called when an object is about to be destroyed. It’s often used for cleanup operations.class Person: def __del__(self): print("Object is being deleted") person = Person() del person # Output: Object is being deleted
7. Class vs Instance Variables
- Class Variables: Shared among all instances of a class. They are defined within the class but outside of methods.
class Dog: species = "Canine" # Class variable def __init__(self, name): self.name = name # Instance variable dog1 = Dog("Buddy") dog2 = Dog("Max") print(dog1.species) # Output: Canine print(dog2.species) # Output: Canine
- Instance Variables: Unique to each instance of the class. They are defined inside methods.
dog1 = Dog("Buddy") print(dog1.name) # Output: Buddy
Summary of Python OOP Concepts
- Class and Object: Blueprint and instances of a class.
- Encapsulation: Bundling data and methods and restricting access to some components.
- Abstraction: Hiding implementation details and providing only necessary interfaces.
- Inheritance: Reusing code from parent classes.
- Polymorphism: Ability for objects of different classes to use the same method name.
- Constructor and Destructor: Special methods to initialize and clean up objects.
- Class vs Instance Variables: Class variables are shared, and instance variables are unique to each object.
OOP allows for better code organization, reusability, and maintenance.