classVehicle:def__init__(self, make:str, year:int):self.make= make
self.year= year
classElectricCar(Vehicle):def__init__(self, make:str, year:int, range_km:int):super().__init__(make, year)self.range_km= range_km
def__repr__(self)->str:return f"{self.year}{self.make} ({self.range_km}km range)"
car =ElectricCar("Tesla",2026,600)print(car)
Output
2026 Tesla (600km range)
Note Always call super().__init__() in the child to ensure the parent is properly initialized. Python supports multiple inheritance via MRO (Method Resolution Order).
classDateRecord:def__init__(self, year:int, month:int, day:int):self.year= year
self.month= month
self.day= day
@classmethod
deffrom_string(cls, date_str:str)->"DateRecord":
y, m, d =map(int, date_str.split("-"))returncls(y, m, d)
@staticmethod
defis_valid_year(year:int)->bool:return1<= year <=9999
record =DateRecord.from_string("2026-04-04")print(record.year,DateRecord.is_valid_year(2026))
Output
2026 True
Note @classmethod receives the class as first arg (cls) and is commonly used for alternative constructors. @staticmethod receives neither self nor cls.
from dataclasses import dataclass
@dataclass
className:
field:type
Example
from dataclasses import dataclass, field
@dataclass
classProduct:
name:str
price:float
tags:list[str]=field(default_factory=list)
@property
defdisplay_price(self)->str:return f"${self.price:.2f}"
p =Product("Widget",9.99,["sale"])print(p)print(p.display_price)
@dataclass(slots=True)classPoint:
x:float
y:float
p =Point(1.0,2.0)print(p)# p.z = 3.0 # AttributeError: no __dict__
Output
Point(x=1.0, y=2.0)
Note __slots__ prevents dynamic attribute creation and reduces memory by eliminating the per-instance __dict__. Python 3.10+ dataclasses support slots=True directly.
from typing importProtocolclassDrawable(Protocol):defdraw(self)->None:...
Example
from typing importProtocolclassSaveable(Protocol):defsave(self, path:str)->None:...classDocument:defsave(self, path:str)->None:print(f"Saved to {path}")defbackup(item:Saveable, dest:str)->None:
item.save(dest)backup(Document(),"/tmp/doc.txt")
Output
Saved to /tmp/doc.txt
Note Protocols enable duck-typing with static type checking. Classes do not need to explicitly inherit from the Protocol; they just need matching methods.
Note __repr__ should produce an unambiguous developer-facing string. __str__ is the user-facing version. Return NotImplemented (not raise) from __eq__ for unknown types.