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:
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
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) |
1 2 3 4 5 6 7 8 9 10 |
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) |
1 2 3 4 5 6 7 8 9 10 11 |
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 🙂