Thursday, 5 March 2026

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

 


Code Explanation:

๐Ÿ”น 1️⃣ Defining Class A
class A:

Creates a class named A

Inherits from object by default

๐Ÿ”น 2️⃣ Overriding __getattribute__
def __getattribute__(self, name):

__getattribute__ is a special method

It is called every time ANY attribute is accessed

It intercepts all attribute lookups

⚠ Important:
This runs even before checking:

Instance attributes

Class attributes

Descriptors

MRO

๐Ÿ”น 3️⃣ Custom Condition
if name == "x":
    return 100

If someone tries to access attribute "x"

It immediately returns 100

Python will NOT continue normal lookup

This overrides everything.

๐Ÿ”น 4️⃣ Calling Parent for Other Attributes
return super().__getattribute__(name)

For all other attributes, we delegate to the normal lookup mechanism

Prevents infinite recursion

⚠ If we wrote:

return self.__dict__[name]

It could cause recursion issues.

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

Creates instance a

a.__dict__ is empty initially

๐Ÿ”น 6️⃣ Assigning Instance Attribute
a.x = 5

This does:

Adds 'x': 5 into a.__dict__

So internally:

a.__dict__ = {'x': 5}

๐Ÿ“Œ Assignment does NOT use __getattribute__
It uses normal attribute setting.

๐Ÿ”น 7️⃣ Accessing a.x
print(a.x)

Here is what happens:

Step-by-step execution:

Python calls:

a.__getattribute__("x")

Inside __getattribute__

name == "x" → True

Immediately returns:

100

It NEVER checks:

a.__dict__

class attributes

MRO

descriptors

✅ Final Output
100

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (119) AI (214) 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 (26) Data Analytics (20) data management (15) Data Science (312) Data Strucures (16) Deep Learning (129) 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 (257) Meta (24) MICHIGAN (5) microsoft (11) Nvidia (8) Pandas (13) PHP (20) Projects (32) Python (1262) Python Coding Challenge (1060) Python Mistakes (50) Python Quiz (435) 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)