Sunday, 21 December 2025

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

 


Code Explanation:


1. Class Definition Starts
class Num:

A class named Num is created.

It will store a number and overload the multiplication operator *.

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


__init__ runs automatically when an object is created.


It receives an argument x.

The value is stored inside the object as instance variable self.x.

So each object of this class holds a number.

3. Defining __mul__ (Operator Overloading)
    def __mul__(self, other):
        return Num(self.x * other.x)

What does this mean?

Python calls __mul__ when the * operator is used.

self refers to the object on the left side of *.

other refers to the object on the right side of *.

Inside the method:

We multiply the numeric values: self.x * other.x

Then create and return a new Num object containing the result.

So:

Using a * b returns another Num object whose value is the product.

4. Creating Two Objects
a = Num(4)
b = Num(3)

a.x = 4

b.x = 3

Both are Num objects, each with a stored integer.

5. Multiplying the Objects
(a * b)

Python translates this into:

a.__mul__(b)


Inside __mul__:

self.x = 4

other.x = 3

Multiply them: 4 * 3 = 12

Return a new Num object containing 12

6. Printing the Stored Result
print((a * b).x)

(a * b) is a new Num object holding the value 12.

Accessing .x prints that integer.

Final Output
12

600 Days Python Coding Challenges with Explanation

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (118) AI (193) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (28) Azure (8) BI (10) Books (262) Bootcamp (1) C (78) C# (12) C++ (83) Course (84) Coursera (299) Cybersecurity (29) data (1) Data Analysis (25) Data Analytics (18) data management (15) Data Science (267) Data Strucures (15) Deep Learning (110) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (18) Finance (9) flask (3) flutter (1) FPL (17) Generative AI (56) Git (9) Google (47) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (233) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (13) PHP (20) Projects (32) Python (1249) Python Coding Challenge (1005) Python Mistakes (46) Python Quiz (413) 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)