Object Orientated Programming with Python – YouTube video – Helpful code
Object orientated programming (OOP) usually is a big matter, however I’ve made up our minds to make a 30 minute video, according to the e book Math for Programmers, as I appreciated how it used to be defined there:
Usually, within the video, I’m speaking about a couple of elementary OOP topics, explaining how those run with Jupyter Pocket book.
My base magnificence is Rectangle, with a couple of dunder strategies and 1 magnificence manner:
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
|
magnificence Rectangle():
def __init__(self, w, h): self.width = w self.peak = h
def space(self): go back self.width * self.peak
def scale(self, issue): go back Rectangle(issue * self.width, issue * self.peak)
def __eq__(self, different): print(f‘Comparability between {str(self)} vs {str(different)}.’) go back self.width == different.width and self.peak == different.peak
def __repr__(self): go back f‘Rectangle {self.width} through {self.peak}’
def __str__(self): go back self.__repr__()
def __mul__(self, issue): go back self.scale(issue)
def __rmul__(self, issue): go back self.scale(issue)
@classmethod def sq.(cls, facet): go back Rectangle(facet, facet) |
One thing, that I’ve now not discussed within the video is the comparability of 2 categories, derived from an summary magnificence, with applied __eq__
:
This is how it’s accomplished:
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
magnificence Form(ABC): @abstractmethod def space(self): go
@abstractmethod def scale(self, issue): go
def __eq__(self,different): print(“From Form(ABC)”) go back self.__dict__ == different.__dict__
def __mul__(self,issue): print(“From Form(ABC)”) go back self.scale(issue)
def __rmul__(self,issue): print(“From Form(ABC)”) go back self.scale(issue) |
|
magnificence Rectangle(Form): def __init__(self,w,h): self.width = w self.peak = h
def space(self): go back self.width * self.peak
def scale(self, issue): go back Rectangle(issue * self.width, issue * self.peak) |
|
from math import pi magnificence Circle(Form):
def __init__(self, r): self.radius = r
def space(self): go back pi * self.radius * self.radius
def scale(self, issue): go back Circle(issue * self.radius) |
And the comparisons appear to be that:
Right here comes the entire code – https://github.com/Vitosh/Python_personal/blob/grasp/YouTube/012_OOP-In-Python/012_OOP-In-Python.ipynb
Experience it 🙂