✕
Class with __init__
class MyClass:
def __init__(self, x: int):
self.x = x
Inheritance
class Child(Parent):
def __init__(self, x: int):
super().__init__(x)
self.extra: str = ""
Abstract class
from abc import ABC, abstractmethod
class Interface(ABC):
@abstractmethod
def method(self) -> None:
pass
Type hints
from typing import List, Optional, Dict
class Repo:
items: List[str]
cache: Optional[Dict[str, int]]
Strategy pattern
class Strategy(ABC):
@abstractmethod
def execute(self) -> None: pass
class Context:
def __init__(self, s: Strategy):
self._strategy = s
def run(self) -> None:
self._strategy.execute()
Observer pattern
class Observer(ABC):
@abstractmethod
def update(self, data) -> None: pass
class Subject:
def __init__(self):
self._observers: List[Observer] = []
def notify(self, data) -> None:
for o in self._observers:
o.update(data)
Singleton pattern
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
Factory method
class Creator(ABC):
@abstractmethod
def create(self) -> Product: pass
def operation(self) -> str:
p = self.create()
return p.do_work()