Code Explanation:
1. Class Definition
class Num:
This defines a new class named Num.
Objects of this class will store a numeric value and support custom division behavior.
2. Constructor Method (__init__)
def __init__(self, x):
self.x = x
__init__ is the constructor that runs when an object is created.
It takes x and stores it inside the object as self.x.
So every Num object holds a number.
3. Operator Overloading (__truediv__)
def __truediv__(self, other):
return Num(self.x - other.x)
__truediv__ defines behavior for the division operator /.
But here division is custom, not mathematical division.
When you do n1 / n2, Python calls this method.
Instead of dividing, it subtracts the values:
→ self.x - other.x
It returns a new Num object containing the result.
4. Creating First Object
n1 = Num(10)
Creates an object n1 with x = 10.
5. Creating Second Object
n2 = Num(4)
Creates an object n2 with x = 4.
6. Performing the “Division”
print((n1 / n2).x)
Calls the overloaded division: n1 / n2.
Internally executes __truediv__:
→ 10 - 4 = 6
Returns Num(6).
.x extracts the value, so Python prints:
6
Final Output
6


0 Comments:
Post a Comment