Skip to content

Instantly share code, notes, and snippets.

@ngshiheng
Last active February 7, 2022 05:46
Show Gist options
  • Save ngshiheng/73c582f27192b36b123cfc15afd8416b to your computer and use it in GitHub Desktop.
Save ngshiheng/73c582f27192b36b123cfc15afd8416b to your computer and use it in GitHub Desktop.
All You Need To Know About Data Classes in Python https://jerrynsh.com/all-you-need-to-know-about-data-classes-in-python/
class Car:
def __init__(self, name: str, brand: str, price: int) -> None:
self.name = name
self.brand = brand
self.price = price
car1 = Car('Model X', 'Tesla', 120_000)
car2 = Car('Model X', 'Tesla', 120_000)
car1 == car2 # False. We need to write our own __eq__ method to handle this.
from dataclasses import dataclass, field
@dataclass
class Car:
name: str = field(compare=False) # To exclude this field from comparison
brand: str = field(repr=False) # To hide fields in __repr__
price: int = 120_000
condition: str = field(default='New')
from dataclasses import dataclass, field
@dataclass
class Car:
name: str = field(compare=False)
brand: str = field(repr=False)
price: int = 120_000
condition: str = field(default='New')
def __post_init__(self):
if self.condition == "Old":
self.price -= 30_000
old_car = Car('Model X', 'Tesla', 130_000, 'Old')
# Car(name='Model X', price=100000, condition='Old')
# ...
from typing import List
@dataclass
class CarDealer:
cars: List[Car]
car3 = Car('Model S', 'Tesla', 89_000)
car4 = Car('Model Y', 'Tesla', 54_000)
car_dealer = CarDealer(cars=[car3, car4])
# CarDealer(cars=[Car(name='Model S', price=89000, condition='New'), Car(name='Model Y', price=54000, condition='New')])
from dataclasses import dataclass
@dataclass
class Car:
name: str # Supports typing out of the box!
brand: str
price: int
car1 = Car('Model X', 'Tesla', 120_000)
car2 = Car('Model X', 'Tesla', 120_000)
car1 == car2 # True. __eq__ is generated automatically.
car2.name # Supports dot annotation!
from collections import namedtuple
Car = namedtuple('Car', ['name', 'brand', 'price'])
car = Car('Model X', 'Tesla', 120_000)
# Using Dictionary
car = {"name": "Model X", "brand": "Tesla", "price": 120_000}
# OR using Tuple
car = ("Model X", "Tesla", 120_000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment