Code Explanation:
1) Import the dataclass decorator
from dataclasses import dataclass
This imports the dataclass decorator from Python’s dataclasses module.
@dataclass automatically creates useful methods (like __init__) for classes.
2) Define the dataclass
@dataclass
class Marks:
@dataclass tells Python to turn Marks into a dataclass.
This means it will auto-generate an initializer (__init__) taking m1 and m2.
3) Declare fields of the class
m1: int
m2: int
These are the attributes of the class.
m1 and m2 are typed as integers, representing two marks.
4) Define a method to compute total
def total(self):
return (self.m1 + self.m2) // 2
total() is an instance method.
It adds the two marks and uses // 2 which performs integer division (floor division).
This returns the average of the two marks as an integer.
5) Create an object and print result
print(Marks(80, 90).total())
Marks(80, 90) creates an object with m1 = 80, m2 = 90.
.total() computes (80 + 90) // 2 = 170 // 2 = 85.
print() displays the result.
Final Output
85
.png)

0 Comments:
Post a Comment