Python OOP Concepts Made Simple: Easy-to-Understand Code Examples
Demystifying OOP Concepts in Python: Classes, Objects, Polymorphism, Encapsulation, Inheritance, and Data Abstraction Made Easy
Here’s an easy-to-understand code example that demonstrates each of the mentioned OOP concepts in Python:
# Class: Define a class named 'Shape'
class Shape:
def __init__(self, color):
self.color = color
# Objects: Create instances of the 'Shape' class
circle = Shape("red")
rectangle = Shape("blue")
# Polymorphism: Define a function that works with different types of shapes
def describe(shape):
print(f"This shape is {shape.color}.")
describe(circle)
describe(rectangle)
# Encapsulation: Use private attributes with getter and setter methods
class BankAccount:
def __init__(self):
self.__balance = 0 # Private attribute
def get_balance(self):
return self.__balance
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
# Inheritance: Create a subclass 'Circle' that inherits from 'Shape'
class Circle(Shape):
def __init__(self, color, radius):
super().__init__(color)
self.radius = radius
# Data Abstraction: Create an abstract class 'Animal'
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def make_sound(self):
pass
# Concrete class 'Dog' inheriting from 'Animal'
class Dog(Animal):
def make_sound(self):
print("Woof!")
# Using the concepts
account = BankAccount()
account.deposit(100)
account.withdraw(30)
print("Balance:", account.get_balance())
circle = Circle("green", 5)
print("Circle color:", circle.color)
dog = Dog()
dog.make_sound()
This example provides an easy way to understand these OOP concepts in Python by demonstrating their use in a simple context.