Object-Oriented Programming (OOP) is a powerful paradigm that allows developers to build software systems by organizing code around objects. Python, with its intuitive syntax and rich set of features, provides an excellent platform for practising OOP principles. In this article, we will explore the core concepts of OOP in Python and demonstrate how to apply them to build robust and maintainable code through practical code examples.
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
def drive(self):
print(f"Driving the {self.make} {self.model}")
my_car = Car("Tesla", "Model S")
my_car.drive() # Output: Driving the Tesla Model S
class BankAccount:
def __init__(self, account_number):
self._account_number = account_number
self._balance = 0
def deposit(self, amount):
self._balance += amount
def withdraw(self, amount):
if amount <= self._balance:
self._balance -= amount
else:
print("Insufficient funds")
def get_balance(self):
return self._balance
account = BankAccount("123456789")
account.deposit(1000)
account.withdraw(500)
balance = account.get_balance()
print(balance) # Output: 500
class Shape:
def __init__(self, color):
self.color = color
def draw(self):
print(f"Drawing a {self.color} shape")
class Circle(Shape):
def __init__(self, color, radius):
super().__init__(color)
self.radius = radius
def draw(self):
print(f"Drawing a {self.color} circle with radius {self.radius}")
my_circle = Circle("red", 5)
my_circle.draw() # Output: Drawing a red circle with radius 5
class Animal:
def sound(self):
pass
class Dog(Animal):
def sound(self):
return "Woof!"
class Cat(Animal):
def sound(self):
return "Meow!"
def make_sound(animal):
print(animal.sound())
dog = Dog()
cat = Cat()
make_sound(dog) # Output: Woof!
make_sound(cat) # Output: Meow!
Object-Oriented Programming in Python offers a structured and efficient approach to software development. By understanding the core concepts of classes, objects, encapsulation, inheritance, and polymorphism, developers can design robust and maintainable code. Through the provided code examples, you have seen how OOP principles can be applied in Python to create functional and reusable solutions. Embrace OOP in Python, and unlock its full potential to elevate your coding practices and create elegant and efficient software solutions.
In Python, the print() function is a fundamental tool for displaying output. While printing simple…
Python is a versatile programming language known for its simplicity and flexibility. When working on…
PDF (Portable Document Format) files are commonly used for sharing documents due to their consistent…
PDF (Portable Document Format) files are widely used for document exchange due to their consistent…
Python is a high-level programming language known for its simplicity and ease of use. However,…
Object-Oriented Programming (OOP), iterators, generators, and closures are powerful concepts in Python that can be…
This website uses cookies.