Sunday, 30 November 2025

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


Code Explanation:

1. Class Definition

class Num:
This line defines a new class named Num, which will hold a number and custom behavior for the + operator.

2. Constructor Method (__init__)

def __init__(self, n):
Defines the constructor that runs whenever a Num object is created.

self.n = n
Stores the passed value n inside the object as an attribute named n.

3. Operator Overloading (__add__)

def __add__(self, o):
Defines how the + operator works for two Num objects.
Here, self is the left operand and o is the right operand.

return Num(self.n - o.n)
Although the operator is +, this function performs subtraction.
It returns a new Num object with value self.n - o.n.

4. Creating Objects

a = Num(9)
Creates a Num object with value 9 and stores it in variable a.

b = Num(4)
Creates another Num object with value 4 and stores it in b.

5. Using the + Operator

print((a + b).n)

Python calls a.__add__(b)

Computes 9 - 4 (because __add__ subtracts)

Creates a new Num object with value 5

(a + b).n accesses the .n value of that object

print prints 5

Output:


700 Days Python Coding Challenges with Explanation

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (118) AI (150) Android (25) AngularJS (1) Api (6) Assembly Language (2) aws (27) Azure (8) BI (10) Books (251) Bootcamp (1) C (78) C# (12) C++ (83) Course (84) Coursera (298) Cybersecurity (28) Data Analysis (24) Data Analytics (16) data management (15) Data Science (216) Data Strucures (13) Deep Learning (67) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (17) Finance (9) flask (3) flutter (1) FPL (17) Generative AI (47) Git (6) Google (47) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (185) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (11) PHP (20) Projects (32) Python (1215) Python Coding Challenge (884) Python Quiz (342) Python Tips (5) Questions (2) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (45) Udemy (17) UX Research (1) web application (11) Web development (7) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)