Object Oriented Programming with Python – YouTube video

Object oriented programming (OOP) in general is a huge topic, but I have decided to make a 30 minute video, based on the book Math for Programmers, as I liked the way it was explained there:

Object Oriented Programming with Python

Generally, in the video, I am talking about a few basic OOP subjects, explaining how these run with Jupyter Notebook.

My base class is Rectangle, with a few dunder methods and 1 class method:

class Rectangle():
    
    def __init__(self, w, h):
            self.width = w
            self.height = h
            
    def area(self):
        return self.width * self.height
    
    def scale(self, factor):
        return Rectangle(factor * self.width, factor * self.height)
    
    def __eq__(self, other):
        print(f'Comparison between {str(self)} vs {str(other)}.')
        return self.width == other.width and self.height == other.height
    
    def __repr__(self):
        return f'Rectangle {self.width} by {self.height}'
    
    def __str__(self):
        return self.__repr__()
    
    def __mul__(self, factor):
        return self.scale(factor)
    
    def __rmul__(self, factor):
        return self.scale(factor)
    
    @classmethod
    def square(cls, side):
        return Rectangle(side, side)

Something, that I have not mentioned in the video is the comparison of two classes, derived from an abstract class, with implemented __eq__:

That is how it is done:

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass
    
    @abstractmethod
    def scale(self, factor):
        pass

    def __eq__(self,other):
        print("From Shape(ABC)")
        return self.__dict__ == other.__dict__

    def __mul__(self,factor):
        print("From Shape(ABC)")
        return self.scale(factor)
    
    def __rmul__(self,factor):
        print("From Shape(ABC)")
        return self.scale(factor)
class Rectangle(Shape):
    def __init__(self,w,h):
        self.width = w
        self.height = h

    def area(self):
        return self.width * self.height
    
    def scale(self, factor):
        return Rectangle(factor * self.width, factor * self.height)
from math import pi
class Circle(Shape):
    
    def __init__(self, r):
        self.radius = r
        
    def area(self):
        return pi * self.radius * self.radius
    
    def scale(self, factor):
        return Circle(factor * self.radius)

And the comparisons look like that:

Here comes the whole code – https://github.com/Vitosh/Python_personal/blob/master/YouTube/012_OOP-In-Python/012_OOP-In-Python.ipynb

Enjoy it 🙂