Tuesday, 7 April 2026

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

 


Code Explanation:

1️⃣ Importing dataclass
from dataclasses import dataclass

Explanation

Imports the dataclass decorator.
It auto-generates methods like __init__, __repr__, etc.

2️⃣ Applying @dataclass
@dataclass

Explanation

Converts class A into a dataclass.
Automatically creates constructor like:
def __init__(self, x=[]):
    self.x = x

⚠️ Important: x=[] is evaluated once, not per object.

3️⃣ Defining Class
class A:

Explanation

Defines class A.

4️⃣ Defining Attribute with Default Value
x: list = []

Explanation ⚠️ CRITICAL

x is given a default value of an empty list.
This list is shared across all instances.

๐Ÿ‘‰ Only ONE list is created in memory.

5️⃣ Creating First Object
a1 = A()

Explanation

a1.x refers to the shared list.

6️⃣ Creating Second Object
a2 = A()

Explanation

a2.x refers to the same shared list.

๐Ÿ‘‰ So:

a1.x is a2.x → True

7️⃣ Modifying List from a1
a1.x.append(1)

Explanation

Adds 1 to the shared list.

๐Ÿ‘‰ Now shared list becomes:

[1]

8️⃣ Printing from a2
print(a2.x)

Explanation

Since a2.x points to the same list:
[1]

๐Ÿ“ค Final Output
[1]

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (119) AI (237) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (28) Azure (10) BI (10) Books (262) Bootcamp (3) C (78) C# (12) C++ (83) Course (87) Coursera (300) Cybersecurity (30) data (5) Data Analysis (29) Data Analytics (21) data management (15) Data Science (339) Data Strucures (16) Deep Learning (144) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (19) Finance (10) flask (4) flutter (1) FPL (17) Generative AI (68) Git (10) Google (51) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (277) Meta (24) MICHIGAN (5) microsoft (11) Nvidia (8) Pandas (13) PHP (20) Projects (32) pytho (1) Python (1284) Python Coding Challenge (1124) Python Mistakes (50) Python Quiz (465) Python Tips (5) Questions (3) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (48) Udemy (18) UX Research (1) web application (11) Web development (8) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)