Code Explanation:
Importing the dataclass decorator
from dataclasses import dataclass
This imports @dataclass, a decorator that automatically adds useful methods to a class (like __init__, __repr__, etc.).
It helps create classes that mainly store data with less code.
Declaring the Product class as a dataclass
@dataclass
class Product:
@dataclass tells Python to automatically create:
an initializer (__init__)
readable string format
comparison methods
The class name is Product, representing an item with price and quantity.
Defining class fields
price: int
qty: int
These define the two attributes the class will store:
price → an integer value
qty → an integer quantity
With @dataclass, Python will automatically create:
def __init__(self, price, qty):
self.price = price
self.qty = qty
Creating a method to compute total cost
def total(self):
return self.price * self.qty
Explanation:
Defines a method named total.
It multiplies the product’s price by qty.
Example: price = 7, qty = 6 → total = 42.
Creating a Product object and printing result
print(Product(7, 6).total())
Breakdown:
Product(7, 6) → Creates a Product object with:
price = 7
qty = 6
.total() → Calls the method to compute 7 × 6 = 42.
print(...) → Displays 42.
Final Output
42
.png)

0 Comments:
Post a Comment