Thursday, 5 March 2026

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

 


Code Explanation:

1️⃣ Defining Class A
class A:

Creates a class named A.

All objects created from this class will use its attributes and methods.

๐Ÿ”น 2️⃣ Defining a Class Attribute
x = 10

x is a class variable.

It belongs to the class A, not to individual objects.

Any instance can access it unless overridden.

So internally:

A.x = 10

๐Ÿ”น 3️⃣ Defining __getattr__
def __getattr__(self, name):
    return 99

This method is called only when an attribute is NOT found normally.

Parameters:

self → the object

name → name of the missing attribute

Behavior here:

If an attribute does not exist, return 99.

Example:

a.unknown → 99

๐Ÿ”น 4️⃣ Creating an Object
a = A()

Creates an instance a of class A.

Internally:

a.__dict__ = {}

The object has no instance attributes yet.

๐Ÿ”น 5️⃣ Printing Two Attributes
print(a.x, a.y)

Python evaluates both attributes separately.

๐Ÿ”น Step 1: Accessing a.x

Python follows attribute lookup order:

1️⃣ Check instance dictionary

a.__dict__

No x found.

2️⃣ Check class attributes

A.x

Found:

10

So Python returns 10.

๐Ÿ“Œ __getattr__ is NOT called because the attribute exists.

๐Ÿ”น Step 2: Accessing a.y

Now Python looks for y.

1️⃣ Instance dictionary
❌ Not found

2️⃣ Class dictionary
❌ Not found

3️⃣ Parent classes (MRO)
❌ Not found

Now Python calls:

__getattr__(self, "y")

Inside the method:

return 99

So the result is 99.

✅ Final Output
10 99

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (119) AI (215) 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 (4) Data Analysis (27) Data Analytics (20) data management (15) Data Science (314) Data Strucures (16) Deep Learning (130) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (19) Finance (10) flask (3) flutter (1) FPL (17) Generative AI (65) 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 (258) Meta (24) MICHIGAN (5) microsoft (11) Nvidia (8) Pandas (13) PHP (20) Projects (32) Python (1263) Python Coding Challenge (1062) Python Mistakes (50) Python Quiz (436) 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)