Sunday, 8 February 2026

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

 


Code Explanation:

1. Defining the descriptor class
class Scale:

This defines a class named Scale.

Objects of this class act as descriptors that control attribute access.

2. Implementing __get__
    def __get__(self, obj, owner):
        return obj.__dict__.get("_x", 1) * 10


__get__ makes Scale a descriptor.

Parameters:

self → the descriptor object (Scale()).

obj → the instance accessing the attribute (i).

owner → the class (Item).

obj.__dict__.get("_x", 1):

Tries to read _x from the instance.

If _x does not exist, it uses default value 1.

The value is then multiplied by 10.

So this descriptor returns a computed value, not a stored one.

3. Defining the owner class
class Item:

This defines a class named Item.

4. Attaching the descriptor
    x = Scale()

x is a class attribute.

It is managed by the Scale descriptor.

Accessing x will trigger Scale.__get__.

5. Creating an instance
i = Item()

An object i of class Item is created.

6. Setting the backing attribute
i._x = 3

_x is a normal instance attribute.

It acts as a backing field used internally by the descriptor.

The descriptor does not store values itself.

7. Accessing the descriptor-managed attribute
print(i.x)

๐Ÿ” What happens when i.x is accessed:

Python finds x in the class Item.

x is a descriptor, so Scale.__get__ is called.

obj.__dict__.get("_x", 1) returns 3.

3 * 10 is calculated.

The final value returned is 30.

✅ Final Output
30

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (118) AI (194) 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 (271) Data Strucures (15) Deep Learning (112) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (18) Finance (9) flask (3) flutter (1) FPL (17) Generative AI (57) 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 (234) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (13) PHP (20) Projects (32) Python (1249) Python Coding Challenge (1008) Python Mistakes (48) Python Quiz (415) 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)