data class

This commit is contained in:
2025-08-24 21:19:54 +05:30
parent 64e8249d43
commit 19437430cc

View File

@ -0,0 +1,50 @@
from dataclasses import dataclass, make_dataclass
from typing import ClassVar, Optional
@dataclass
class Car:
# Instance variables (required first)
name: str
color: str
year: int = 2025 # default value
price: Optional[float] = None # nullable (Optional)
# Class variable (static) - shared by all cars
extra_wheels: int = 1
# Car(name='BMW', color='black', year=2025, price=None, extra_wheels=1)
wheels: ClassVar[int] = 4 # wont appear in __init__, shared by all
# Car(name='BMW', color='black', year=2025, price=None, extra_wheels=1)
# Custom string output
car = Car(name="BMW", color="black")
print(car)
# -----------------------------------------------------
# fields dynamic
field_definitions = [
("name", str, "Unknown"),
("color", str, "Black"),
("year", int, 2025),
("price", Optional[float], None),
]
# Add more fields dynamically (simulate 30+ attributes)
for i in range(5, 35):
field_definitions.append((f"attr{i}", Optional[str], None))
# Step 2: Create dataclass dynamically
Bus = make_dataclass("Bus", field_definitions)
bus = Bus()
bus.attr32 = "46"
print(bus)