Wednesday, 25 February 2026

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

 


Code Explanation:

1. Defining the Descriptor Class

class D:

Creates a class D

This class is meant to act as a descriptor

๐Ÿ”น 2. Implementing the __get__ Method

def __get__(self, obj, objtype):

    return 99

__get__ controls attribute access

Called whenever x is read (a.x)

Always returns 99

Parameters:

self → descriptor object

obj → instance accessing the attribute (a)

objtype → owner class (A)

๐Ÿ”น 3. Implementing the __set__ Method

def __set__(self, obj, value):

    pass

__set__ controls attribute assignment

Called when a.x = 5

pass means do nothing

No instance attribute is created

๐Ÿ“Œ Important:

Having __set__ makes this a DATA DESCRIPTOR.

๐Ÿ”น 4. Why This Is a Data Descriptor (Very Important)

A descriptor that defines:

__get__ and/or __set__

is a DATA DESCRIPTOR

๐Ÿ“Œ Data descriptors have higher priority than:

Instance attributes

Non-data descriptors

๐Ÿ”น 5. Defining Class A

class A:

    x = D()

x is a class attribute

Value is an instance of D

Since D is a data descriptor, x is managed by the descriptor

๐Ÿ”น 6. Creating an Instance of A

a = A()

Creates object a

a.__dict__ is empty at this point

๐Ÿ”น 7. Assigning to a.x

a.x = 5

What happens internally:

Python sees assignment to x

Finds that x is a data descriptor

Calls:

D.__set__(x_descriptor, a, 5)

__set__ does nothing (pass)

No instance attribute is created

๐Ÿ“Œ So a.__dict__ still does not contain x

๐Ÿ”น 8. Accessing a.x

print(a.x)

Attribute lookup order:

Data descriptor → ✅ found

Instance dictionary → skipped

Class attributes → skipped

Python calls:

D.__get__(x_descriptor, a, A)

Which returns 99

✅ Final Output

99

900 Days Python Coding Challenges with Explanation

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 (8) BI (10) Books (262) Bootcamp (1) C (78) C# (12) C++ (83) Course (84) Coursera (299) Cybersecurity (29) data (1) 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 (9) 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 (9) Nvidia (8) Pandas (13) PHP (20) Projects (32) Python (1258) Python Coding Challenge (1048) 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)