Python 3 Deep Dive Part 4 Oop ✭

This report assumes you have a basic understanding of Python classes but want to explore the deeper mechanics, advanced patterns, and internals of Python’s OOP model.


Welcome to Part 4 of the Python 3 Deep Dive series, where we'll explore the world of Object-Oriented Programming (OOP) in Python. In this section, we'll cover the fundamental concepts of OOP, including classes, objects, inheritance, polymorphism, and more.

class Multiplier:
    def __init__(self, factor):
        self.factor = factor
    def __call__(self, x):
        return x * self.factor

double = Multiplier(2) print(double(5)) # 10


Protocols (from typing) define interfaces via structural subtyping without inheritance. python 3 deep dive part 4 oop

from typing import Protocol

class Drawable(Protocol): def draw(self) -> None: ...

class Triangle: def draw(self) -> None: print("Triangle")

def render(obj: Drawable) -> None: obj.draw()

render(Triangle()) # OK – Triangle implements the protocol This report assumes you have a basic understanding

Contrast with ABC: no explicit inheritance, just "looks like a duck".


Inheritance is a fundamental concept in OOP that allows one class to inherit the attributes and methods of another class. The class that is being inherited from is called the parent or superclass, and the class that is doing the inheriting is called the child or subclass.

Here's an example of inheritance in Python 3: Welcome to Part 4 of the Python 3

class ElectricCar(Car):
    def __init__(self, make, model, year, battery_size):
        super().__init__(make, model, year)
        self.battery_size = battery_size
def charge(self):
        print("Charging...")

In this example, the ElectricCar class inherits from the Car class using the (Car) syntax. The super().__init__ method is used to call the __init__ method of the parent class.

The ElectricCar class also has its own attribute battery_size and method charge.

class Temperature:
    def __init__(self, celsius):
        self._celsius = celsius
@property
def celsius(self):
    return self._celsius
@celsius.setter
def celsius(self, value):
    if value < -273.15:
        raise ValueError("Below absolute zero")
    self._celsius = value