Code Explanation:
1. Importing dataclass
from dataclasses import dataclass
Explanation:
Imports the dataclass decorator from Python’s dataclasses module.
@dataclass helps automatically generate methods like __init__, __repr__, etc.
2. Creating a Data Class
@dataclass
class Item:
Explanation:
@dataclass tells Python to treat Item as a dataclass.
Python will auto-generate an initializer and other useful methods.
3. Declaring Attributes
name: str
price: int
qty: int
Explanation:
These are type-annotated fields.
name → string
price → integer
qty → integer
The dataclass generates an __init__ method using these.
4. Creating an Object
item = Item("Pen", 10, 5)
Explanation:
Creates an instance of Item.
Sets:
name = "Pen"
price = 10
qty = 5
5. Performing Calculation and Printing
print(item.price * item.qty)
Explanation:
Accesses price → 10
Accesses qty → 5
Multiplies: 10 × 5 = 50
Prints 50.
Final Output:
50


0 Comments:
Post a Comment