09 Python OOP
Object-Oriented Programming (OOP) is a method of structuring a program by bundling related properties and behaviors into individual objects.
9.1 4 Principles of OOP
There are 4 major principles that make a language Object-Oriented. These are Encapsulation, Data Abstraction, Polymorphism, and Inheritance. These are also called the four pillars of Object-Oriented Programming.
9.1.1 Encapsulation
Encapsulation is achieved when each object keeps its state private, inside a class. Other objects don’t have direct access to this state. Instead, they can only call a list of public functions — called methods.
Example
class Person:
def __init__(self, name, age):
self.__name = name
self.__age = age
def get_name(self):
return self.__name
def get_age(self):
return self.__age
def set_age(self, age):
if age > 0:
self.__age = age
p = Person("John", 30)
print(p.get_name()) # John
print(p.get_age()) # 30
p.set_age(31)
print(p.get_age()) # 31
9.1.2 Abstraction
- Data Abstraction is a way of creating a simple model of more complex real-world entities, which contains only the important properties from the perspective of the context of an application.
- OOP Abstraction uses abstract classes or interfaces to express the intent of the class rather than the actual implementation.
https://learntocodetogether.com/what-the-heck-is-oop/
Example
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
return "Bark"
class Cat(Animal):
def sound(self):
return "Meow"
d = Dog()
c = Cat()
print(d.sound()) # Bark
print(c.sound()) # Meow
9.1.3 Inheritance
In OOP, the child class could reuse all method of parents class.(Except the private members in some advance language).
All child is a
type of parents.
for example, car is type of vehicle, bird is type of animal, chicken is type of bird, etc.
Example
class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def drive(self):
print("Driving")
class Car(Vehicle):
def __init__(self, brand, model, doors):
super().__init__(brand, model)
self.doors = doors
def honk(self):
print("Honking")
c = Car("Toyota", "Corolla", 4)
c.drive() # Driving
c.honk() # Honking
9.1.4 Polymorphism
Polymorphism means each child class can have different behaviors through inheriting the same method from the parent class.
class Animal(object):
def __init__(self, name):
self.name = name
def talk(self):
raise NotImplementedError
class Dog(Animal):
def talk(self):
return "Bow...Bow..."
class Cat(Animal):
def talk(self):
return "Meow...Meow..."
class Human(Animal):
def talk(self):
return "I can talk more...."
Example
def animal_sound(animal):
print(animal.talk())
d = Dog("Dog")
c = Cat("Cat")
h = Human("Human")
animal_sound(d) # Bow...Bow...
animal_sound(c) # Meow...Meow...
animal_sound(h) # I can talk more....
9.2 Example of OOP in Python
9.2.1 Animal Example 1
The example below shows the Animal, Dog, and Turtle classes in OOP.
class Animal:
def __init__(self, name):
self.name = name
print(self.name + " was adopted.")
def run(self):
print("running!")
class Dog(Animal):
def __init__(self, name):
self.name = name
print(self.name + " was adopted.")
def bark(self):
print("woof!")
class Turtle(Animal):
def __init__(self, name):
super().__init__(name)
def run(self):
print("running slowly!")
# We don't care how it works, just bark
spot = Dog("spot") #=> spot was adopted.
spot.bark() #=> woof!
# Dog inherits the run method from Animal
spot.run() #=> running!
# We get back an interesting response
tim = Turtle("tim") #=> tim was adopted.
tim.run() #=> running slowly!
9.2.2 Animal Example 2
Below is a more complex example of Inheritance and Polymorphism.
class Animal:
def __init__(self, name, gender):
self.name = name
self.gender = gender
def __str__(self) -> str:
return "class={}: name:{} gender:{}".format(type(self).__name__, self.name, self.gender)
class Bird(Animal):
def __init__(self, name, gender):
Animal.__init__(self, name, gender)
def flying(self):
return "birds flying..."
class Chicken(Bird):
def __init__(self, name, gender):
super().__init__(name, gender) # In Python 3 and above, you can use super() to initialize the parent without self
self.gender = gender
def flying(self):
return "chicken {} can't fly..".format(self.name)
class CanadianGoose(Bird):
def __init__(self, name, gender):
Bird.__init__(self, name, gender)
def swimming(self):
return "Canadian Goose floating on the water.."
aHen = Chicken("egg hatcher", "F")
aRooster = Chicken("big Foot", "M")
aGoose = CanadianGoose("wild goose", "unknown")
print(aHen.flying())
print(aGoose.flying())
print(aGoose.swimming())
print(aRooster)
9.3 Homework
Please practice OOP by writing classes Vehicle
, Car
, and Truck
.
Exercise
- Create a class
Shape
with a methodarea
. - Create two subclasses
Square
andCircle
that implement thearea
method. - Write a function that takes a list of shapes and prints the area of each shape.
Quiz
- What is Encapsulation?
- How does Inheritance work in OOP?
- Explain Polymorphism with an example.
- What is the difference between Abstraction and Encapsulation?
9.4 References
Read more if you need to understand more about OOP in Python:
- https://www.w3schools.com/python/python_inheritance.asp
- https://realpython.com/python3-object-oriented-programming/
- https://learnbatta.com/course/python/python-object-oriented-programming/
- https://medium.com/@cancerian0684/what-are-four-basic-principles-of-object-oriented-programming-645af8b43727
- https://dev.to/terrythreatt/the-four-principles-of-object-oriented-programming-in-python-1jbi
9.5 Interactive Learning
Use platforms like Repl.it or Jupyter Notebooks to write and test your code interactively.
9.6 Real-World Applications
Explore how OOP principles are used in real-world applications like game development, GUI applications, and web development.