Learn Python from Scratch 2023: Module 5
Module 5: Object-Oriented Programming
Object-Oriented Programming (OOP) is a programming paradigm that focuses on the creation of objects that have properties and methods. Python is an object-oriented programming language, which means that everything in Python is an object.
- Classes and Objects
A class is a blueprint for creating objects, and an object is an instance of a class. In Python, classes are defined using the class
keyword. Here is an example:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print("Woof!")
In this example, we define a class called Dog
with two attributes: name
and age
. We also define a method called bark
, which prints "Woof!" when called.
To create an object of this class, we can simply call the class with the required arguments:
my_dog = Dog("Rufus", 3)
Now, my_dog
is an instance of the Dog
class, with the name "Rufus" and age 3.
2. Inheritance
Inheritance is a way to create a new class that is a modified version of an existing class. The new class inherits all the attributes and methods of the existing class, and can also have additional attributes and methods. In Python, inheritance is defined using the super()
function. Here is an example:
class Poodle(Dog):
def __init__(self, name, age, color):
super().__init__(name, age)
self.color = color
def dance(self):
print("The poodle is dancing!")
In this example, we define a new class called Poodle
, which inherits from the Dog
class. The Poodle
class has an additional attribute called color
, and a new method called dance
.
To create an object of the Poodle
class, we can call the class with the required arguments:
my_poodle = Poodle("Fifi", 2, "white")
Now, my_poodle
is an instance of the Poodle
class, with the name "Fifi", age 2, and color "white".
3. Polymorphism
Polymorphism is the ability of objects to take on different forms depending on the context in which they are used. In Python, polymorphism is achieved through method overriding and method overloading.
Method overriding is when a subclass defines a method with the same name as a method in the superclass, and the subclass’s method overrides the superclass’s method. Here is an example:
class Animal:
def __init__(self, name):
self.name = name
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
return "Woof!"
class Cat(Animal):
def make_sound(self):
return "Meow!"
animals = [Dog("Fido"), Cat("Fluffy")]
for animal in animals:
print(animal.name + ": " + animal.make_sound())
In this example, we defined a base class called “Animal” and two derived classes called “Dog” and “Cat”. Each class has a method called “make_sound” that returns a different sound. We created a list called “animals” with one object of each class. We then looped through the list and called the “make_sound” method for each object, which printed out the name of the animal and the sound it makes.