Object-Oriented Principles are listed below:
- Classes and Objects
- Encapsulation
- Inheritance
- Polymorphism
- Abstraction
1.) Classes and Objects:
- A class is a blueprint for creating objects. It defines the properties (attributes) and behaviors (methods) of objects.
- An object is an instance of a class. It represents a real-world entity.
Example:
class Car:
brand = "mercedes"
model = "2025"
car1 = Car()
print(car1.brand)
print(car1.model)2.) Encapsulation:
Encapsulation is the bundling of data and methods into a single unit (class) and restricting direct access to some attributes.
Example:
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private variable
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # Output: 15003.) Inheritance:
Inheritance is the OOP feature that allows a class (called a subclass or child class) to acquire the properties and behaviors (methods and attributes) of another class (called a superclass or parent class), promoting code reuse.
Example:
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Dog barks")
dog = Dog()
dog.speak() # Output: Dog barks4.) Polymorphism:
Polymorphism allows objects of different classes to be treated as objects of a common superclass, particularly enabling the same method name to behave differently depending on the object that invokes it.
Example:
class Bird:
def sound(self):
print("Some generic bird sound")
class Sparrow(Bird):
def sound(self):
print("Chirp chirp")
sparrow = Sparrow()
sparrow.sound() # Output: Chirp chirp5.) Abstraction:
Abstraction is the concept of hiding the internal implementation details of a class and showing only the essential features to the user, typically achieved using abstract classes or interfaces.
Example:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
circle = Circle(5)
print(circle.area()) # Output: 78.5