Code Explanation:
Import the dataclass decorator
from dataclasses import dataclass
Imports the @dataclass decorator from Python’s dataclasses module.
@dataclass automatically generates useful methods like:
__init__() → constructor
__repr__() → string representation
Define the Product dataclass
@dataclass
class Product:
Declares a class Product as a dataclass.
Dataclasses are useful for storing data with minimal boilerplate.
Declare class fields
price: int
qty: int
These are the two attributes of the class:
price → the price of the product
qty → the quantity of the product
With @dataclass, Python automatically creates an __init__ method that initializes these fields.
Create objects and perform calculation
print(Product(9, 7).price * 2 + Product(9, 7).qty)
Product(9, 7) → Creates a Product object with price = 9 and qty = 7.
.price * 2 → 9 * 2 = 18
+ Product(9, 7).qty → 18 + 7 = 25
print() → Outputs 25.
Final Output
25
.png)

0 Comments:
Post a Comment