Code Explanation:
1. Class definition
class Num:
Defines a class named Num. Instances of Num will hold a numeric value and support a custom subtraction behavior.
2. Constructor (__init__)
def __init__(self, x):
self.x = x
__init__ runs when a Num object is created.
It accepts parameter x and stores it on the instance as self.x.
3. Overloading subtraction (__sub__)
def __sub__(self, other):
return Num(self.x // other.x)
__sub__ is a magic method that defines what a - b does when a and b are Num objects.
Inside, it computes the floor division of the two stored values: self.x // other.x.
Floor division // divides and then rounds down to the nearest integer.
It creates and returns a new Num object initialized with that result (original objects are not modified).
4. Create first object
n1 = Num(20)
Instantiates n1 with x = 20.
5. Create second object
n2 = Num(3)
Instantiates n2 with x = 3.
6. Subtract and print the result
print((n1 - n2).x)
n1 - n2 calls Num.__sub__: computes 20 // 3 which equals 6.
__sub__ returns a new Num object with x = 6.
(n1 - n2).x accesses that new object’s x attribute.
print outputs:
6
Final output
6


0 Comments:
Post a Comment