Thursday, 26 February 2026

Python Coding challenge - Day 1052| What is the output of the following Python Code?

 


Code Explanation:

1. Defining the Class
class Num:

This line defines a class named Num.

A class is a blueprint for creating objects.

2. Constructor Method (__init__)
def __init__(self, x):
    self.x = x

__init__ is called automatically when an object is created.

self refers to the current object.

self.x = x stores the value of x inside the object.

3. Overloading the + Operator
def __add__(self, other):

__add__ is a special (magic) method.

It is called when the + operator is used between two Num objects.

self → left operand

other → right operand

4. Modifying the Object Inside __add__
self.x += other.x

Adds other.x to self.x.

This changes the value of self.x permanently.

Here, the original object (a) is modified.

5. Returning the Object
return self

Returns the same object (self) after modification.

No new object is created.

6. Creating Object a
a = Num(5)

Creates an object a.

a.x is initialized to 5.

7. Creating Object b
b = Num(3)

Creates another object b.

b.x is initialized to 3.

8. Adding Objects
c = a + b

Calls a.__add__(b).

self → a, other → b.

a.x becomes 5 + 3 = 8.

self (which is a) is returned.

c now refers to the same object as a.

9. Printing the Values
print(a.x, b.x, c.x)

a.x → 8 (modified)

b.x → 3 (unchanged)

c.x → 8 (same as a.x)

10. Final Output
8 3 8

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (119) AI (211) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (28) Azure (9) BI (10) Books (262) Bootcamp (1) C (78) C# (12) C++ (83) Course (86) Coursera (300) Cybersecurity (29) data (2) Data Analysis (26) Data Analytics (20) data management (15) Data Science (305) Data Strucures (16) Deep Learning (127) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (18) Finance (10) flask (3) flutter (1) FPL (17) Generative AI (64) Git (10) Google (50) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (252) Meta (24) MICHIGAN (5) microsoft (10) Nvidia (8) Pandas (13) PHP (20) Projects (32) Python (1259) Python Coding Challenge (1050) Python Mistakes (50) Python Quiz (431) Python Tips (5) Questions (3) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (46) Udemy (17) UX Research (1) web application (11) Web development (8) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)