Object-Oriented Programming (OOP) in Python provides a way to organize code by grouping related data and functions into classes. Key concepts include classes, inheritance, and polymorphism.
Object-Oriented Programming in Python
1. What is a Class?
A class is a blueprint for creating objects. Each object created from a class is called an instance, containing its own data and methods.
Creating a Class
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return "Woof!"
Here, Dog
is a class with an initializer method __init__
and a method bark()
. The self
parameter refers to the instance.
Creating an Instance
dog1 = Dog("Buddy", 3)
print(dog1.name) # Output: Buddy
print(dog1.bark()) # Output: Woof!
Classes Quiz
What is the purpose of the __init__
method?
What does self
refer to in a class method?
2. Inheritance
Inheritance allows a class to inherit attributes and methods from another class, promoting code reuse and creating a hierarchy of classes.
Example of Inheritance
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def bark(self):
return "Woof!"
Here, Dog
inherits from Animal
, meaning it has access to the name
attribute defined in Animal
.
Using the Inherited Class
dog1 = Dog("Buddy")
print(dog1.name) # Output: Buddy
print(dog1.bark()) # Output: Woof!
Inheritance Quiz
What is the main benefit of inheritance?
How do you indicate a class inherits from another class?
3. Polymorphism
Polymorphism allows different classes to be treated as instances of the same class through shared methods, promoting flexibility in code.
Example of Polymorphism
class Cat:
def speak(self):
return "Meow!"
class Dog:
def speak(self):
return "Woof!"
def make_animal_speak(animal):
print(animal.speak())
Both Cat
and Dog
have a speak()
method, allowing make_animal_speak()
to call speak()
on any object passed to it:
dog = Dog()
cat = Cat()
make_animal_speak(dog) # Output: Woof!
make_animal_speak(cat) # Output: Meow!
Polymorphism Quiz
What is the key requirement for polymorphism to work?
What is the output if we add make_animal_speak(5)
?
4. Encapsulation
Encapsulation restricts access to specific parts of an object, using private methods and variables to protect the internal state.
Example of Encapsulation
class BankAccount:
def __init__(self, balance=0):
self.__balance = balance
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def get_balance(self):
return self.__balance
Here, __balance
is a private variable, only accessible within the class through the get_balance()
method.
Encapsulation Quiz
How do you indicate a private variable in Python?
What is the main purpose of encapsulation?