Friday, 10 April 2026

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

 


Code Explanation:

๐Ÿ”น 1. Class Definition
class Test:
    x = []
✅ Explanation:
A class named Test is created.
x = [] is a class variable (shared by all objects).
This means:
Only one list exists in memory.
All instances (a, b, etc.) will refer to the same list unless overridden.

๐Ÿ”น 2. Constructor (__init__ method)
def __init__(self, value):
    self.x.append(value)

✅ Explanation:
This method runs whenever an object is created.
self refers to the current object.
self.x.append(value):
Python first looks for x inside the instance.
Not found → it looks in the class.
Finds x (the shared list).
So, it appends the value to the same shared list.

๐Ÿ”น 3. Creating First Object
a = Test(1)
✅ What happens:
Object a is created.
__init__(1) runs.
self.x.append(1) → list becomes:
[1]

๐Ÿ”น 4. Creating Second Object
b = Test(2)
✅ What happens:
Object b is created.
__init__(2) runs.
Again, self.x refers to the same class list.
2 is appended → list becomes:
[1, 2]

๐Ÿ”น 5. Printing Values
print(a.x, b.x)
✅ Explanation:
Both a.x and b.x refer to the same list.
So output is:
[1, 2] [1, 2]

⚠️ Key Concept (Very Important)
๐Ÿ”ธ Class Variable vs Instance Variable
Type Defined Where Shared?
Class Variable Inside class ✅ Yes
Instance Variable Inside __init__ using self ❌ No
๐Ÿ”ฅ Why This Happens

Because:

x = []

is defined at class level, not inside __init__.

✅ How to Fix (If You Want Separate Lists)
class Test:
    def __init__(self, value):
        self.x = []      # instance variable
        self.x.append(value)

✔️ Output now:
[1] [2]

๐ŸŽฏ Final Answer
[1, 2] [1, 2]

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (119) AI (241) 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 (342) Data Strucures (16) Deep Learning (146) 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 (280) Meta (24) MICHIGAN (5) microsoft (11) Nvidia (8) Pandas (13) PHP (20) Projects (32) pytho (1) Python (1291) Python Coding Challenge (1125) Python Mistakes (51) Python Quiz (468) 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)