Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around data, or objects, rather than functions and logic. Python is a powerful object-oriented language, and understanding OOP is key to writing reusable, maintainable, and efficient code.
7.1 Classes and Objects
In Python, a class is a blueprint for creating objects (a particular data structure), and an object is an instance of a class. Classes encapsulate data for the object and methods to manipulate that data.
# Example of a class and object in Python
class Car:
# Constructor
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
# Method to display car details
def display_info(self):
print(f"Car: {self.year} {self.make} {self.model}")
# Create an object (instance) of the class
my_car = Car("Toyota", "Camry", 2022)
my_car.display_info()
In this example, the Car class has attributes for the car’s make, model, and year. The display_info method prints the car's details. We then create an instance my_car and call the method.
7.2 Inheritance
Inheritance allows one class (child) to inherit attributes and methods from another class (parent). This promotes code reuse and makes it easy to maintain.
# Example of inheritance in Python
class Vehicle:
def __init__(self, make, model):
self.make = make
self.model = model
def start(self):
print(f"{self.make} {self.model} is starting...")
class Car(Vehicle):
def __init__(self, make, model, year):
super().__init__(make, model) # Call the parent class constructor
self.year = year
def display_info(self):
print(f"Car: {self.year} {self.make} {self.model}")
# Create an instance of Car
my_car = Car("Honda", "Civic", 2021)
my_car.start()
my_car.display_info()
In this example, the Car class inherits from the Vehicle class. It uses the parent’s start method and also adds its own method display_info.
7.3 Polymorphism
Polymorphism allows methods to be used interchangeably between different object types. This means that different objects can respond to the same method call in different ways.
# Example of polymorphism in Python
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
# Function that uses polymorphism
def animal_sound(animal):
print(animal.speak())
# Create instances of Dog and Cat
dog = Dog()
cat = Cat()
# Call the same function on different objects
animal_sound(dog) # Output: Woof!
animal_sound(cat) # Output: Meow!
In this example, both the Dog and Cat classes have a speak method, but they behave differently. The animal_sound function can handle both types of objects without needing to know their specific class.
7.4 Encapsulation
Encapsulation restricts direct access to some of an object's components, which is a way of preventing accidental modification of data. In Python, encapsulation is achieved by using single or double underscores to indicate "private" or "protected" members.
# Example of encapsulation in Python
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.__balance = balance # Private attribute
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
# Create an instance of BankAccount
account = BankAccount("John", 1000)
account.deposit(500)
print(account.get_balance()) # Output: 1500
# Trying to access a private attribute directly will raise an error
# print(account.__balance) # This will raise an AttributeError
In this example, the BankAccount class encapsulates the __balance attribute, and it can only be accessed via the get_balance method, not directly.
Comments
Post a Comment