Code Explanation:
1. Class Definition
class Num:
A class named Num is created.
Objects of this class will store a number and support custom operations (like %).
2. Constructor Method
def __init__(self, x):
self.x = x
__init__ runs when a new Num object is created.
It assigns the input value x to the instance variable self.x.
Example: Num(20) → self.x = 20.
3. Operator Overloading: __mod__
def __mod__(self, other):
return Num(self.x // other.x)
This method is called when you use the % operator on Num objects.
Instead of normal modulo, this custom method performs floor division (//).
It returns a new Num object holding the result.
Example: 20 // 3 = 6.
4. Creating the First Object
n1 = Num(20)
Creates an object n1 where n1.x = 20.
5. Creating the Second Object
n2 = Num(3)
Creates an object n2 where n2.x = 3.
6. Using the % Operator
print((n1 % n2).x)
Calls n1.__mod__(n2) internally.
Computes 20 // 3 = 6.
Returns a new Num object with x = 6.
.x extracts the stored value.
Final Output
6


0 Comments:
Post a Comment