Code Explanation:
๐น 1. Importing NamedTuple
from typing import NamedTuple
✅ Explanation
NamedTuple is imported from Python's built-in typing module.
It is used to create tuple-like objects with named fields.
Unlike a normal tuple where values are accessed using indexes, NamedTuple allows access using meaningful names.
Think of it as a tuple with labels.
Normal Tuple
↓
(2, 5)
Access
↓
point[0]
point[1]
NamedTuple
↓
x → 2
y → 5
Access
↓
point.x
point.y
๐น 2. Creating the Point Class
class Point(NamedTuple):
✅ Explanation
A new class named Point is created.
But unlike a normal class,
class Point:
this class automatically behaves like a tuple.
Python prepares a class that will store fixed values.
Memory
Point
↓
NamedTuple Class
Nothing is stored yet.
๐น 3. Declaring the First Field
x: int
✅ Explanation
This line creates the first field.
Field Name
x
Expected Type
int
This means every Point object will have an attribute called x.
Current Structure
Point
↓
x
↓
Integer
๐น 4. Declaring the Second Field
y: int
✅ Explanation
Another field named y is created.
Expected type
Integer
Now the class structure becomes
Point
↓
x → int
y → int
These are only field definitions.
No object exists yet.
๐น 5. Creating an Object
p = Point(2, 5)
✅ Explanation
Python creates a new object.
Internally it behaves almost like
(2, 5)
But now the values have names.
Current Memory
p
↓
Point
↓
x → 2
y → 5
Unlike a normal tuple,
you can access
p.x
p.y
instead of
p[0]
p[1]
๐น 6. Accessing the First Field
p.x
✅ Explanation
Python looks inside the object.
Current Object
Point
↓
x → 2
y → 5
Value returned
2
๐น 7. Accessing the Second Field
p.y
✅ Explanation
Python again looks inside the same object.
Current Object
Point
↓
x → 2
y → 5
Value returned
5
๐น 8. Adding the Values
p.x + p.y
✅ Explanation
Python performs the addition.
Calculation
2 + 5
↓
7
Returned value
7
๐น 9. Printing the Result
print(p.x + p.y)
✅ Explanation
Python prints the calculated result.
Output
7
๐ฏ Final Output
7

0 Comments:
Post a Comment