Tuesday, 6 October 2026

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

 


Code Explanation:

1. ๐Ÿ—️ Create the Descriptor Class
class D:


A class D is created.
This class will act as a descriptor because it defines the special method __get__().
2. ๐Ÿ” Define __get__()
def __get__(self, obj, owner):


__get__() controls what happens when the descriptor attribute is read.
Here:
- obj → the instance accessing the attribute
- owner → the class that owns the descriptor
For a.x:
obj   → a
owner → A

3. ๐ŸŽฏ Return 50
return 50


Whenever the descriptor's value is retrieved, it returns:
50

So the descriptor does not return the value stored in the instance dictionary.
4. ๐Ÿ“Œ Put Descriptor in Class A
class A:    x = D()


Here:
A.x → D object

The object created by D() is assigned to A.x.
Because D defines __get__(), x becomes a descriptor.
5. ๐Ÿ†• Create Object a
a = A()


An instance of A is created.
At this point, a doesn't have an "x" entry in its own __dict__.
6. ๐Ÿ“ Manually Add x to a.__dict__
a.__dict__["x"] = 100


Now the instance dictionary contains:
a.__dict__


which is approximately:
{'x': 100}

So it may look like:
a.x

should return 100.
But there is an important descriptor rule.
7. ⚡ Access a.x
print(a.x)


Python sees that A.x is a non-data descriptor because D has __get__() but does not have __set__() or __delete__().
Normally, an instance attribute can override a non-data descriptor.
So in fact, this code:
a.__dict__["x"] = 100


means the instance value wins.
Therefore:
a.x → 100

✅ Correct Final Output
100

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (119) AI (347) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (31) Azure (12) BI (10) book (1) Books (359) Bootcamp (16) C (78) C# (12) C++ (83) cloud (1) Course (93) Coursera (305) Cybersecurity (36) data (10) Data Analysis (47) Data Analytics (31) data management (16) Data Science (435) Data Strucures (19) Deep Learning (222) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (9) Excel (24) Finance (13) flask (4) flutter (1) FPL (17) Gadgets (1) Generative AI (78) Git (13) Google (55) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (43) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (407) Meta (24) MICHIGAN (5) microsoft (13) Nvidia (8) Pandas (16) PHP (20) Projects (35) Python (1378) Python Coding Challenge (1269) Python Library (19) Python Mathematics (19) Python Mistakes (51) Python Pattern Challenge (17) Python Quiz (652) Python Tips (112) Questions (3) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (21) SQL (55) Udemy (22) UX Research (1) web application (11) Web development (9) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)