Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. Object-oriented Programmi...
  5. Object-Oriented Principles

Object-Oriented Principles

Object-Oriented Principles are listed below:

  • Classes and Objects
  • Encapsulation
  • Inheritance
  • Polymorphism
  • Abstraction
  • 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)

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: 1500

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 barks

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 chirp

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

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *