Code Explanation:
1. Class Definition
class Num:
This defines a new class called Num.
Each object of this class represents a number stored in the attribute x.
The class will also define how objects behave when used with operators like +.
2. Constructor Method
def __init__(self, x):
self.x = x
__init__ is the constructor method, called automatically when a new object is created.
x is a parameter passed during object creation.
self.x = x stores the value of x inside the object as an instance attribute.
3. Operator Overloading (+)
def __add__(self, other):
return Num(self.x * other.x)
__add__ is a magic method that defines the behavior of the + operator.
self is the current object, other is another object of the same class.
Instead of normal addition, this method multiplies the x values of the two objects and returns a new Num object.
4. Creating Object n1
n1 = Num(3)
This creates a Num object n1 with x = 3.
The constructor __init__ is called automatically.
5. Creating Object n2
n2 = Num(4)
This creates a second Num object n2 with x = 4.
6. Using + Operator
print((n1 + n2).x)
n1 + n2 calls the __add__ method.
Inside __add__, it multiplies n1.x * n2.x = 3 * 4 = 12.
Returns a new Num object with x = 12.
(n1 + n2).x accesses the x attribute of the new object.
print outputs:
12
Summary
Num objects can use +, but it multiplies values instead of adding.
__add__ returns a new object, leaving original objects unchanged.
Output :
12


0 Comments:
Post a Comment