Monday, 1 September 2025

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

 


Code Explanation:

1) class A:

Defines a new class A.

Inside this class, both class variables and methods will be defined.

2) val = 5

Declares a class variable val with value 5.

This belongs to the class itself, not to any specific object.

Accessible as A.val.

3) def __init__(self, v):

Defines the constructor of the class.

It runs automatically when you create a new object of class A.

Parameter v is passed during object creation.

4) self.val = v

This creates/overwrites an instance variable val on the object itself.

Instance variables take precedence over class variables when accessed through the object.

So now, self.val (object’s variable) will hide A.val (class variable) for that instance.

5) a1 = A(10)

Creates object a1 of class A.

Calls __init__ with v = 10.

Inside __init__, a1.val = 10.

Now a1 has its own instance variable val = 10.

6) a2 = A(20)

Creates another object a2.

Calls __init__ with v = 20.

Inside __init__, a2.val = 20.

Now a2 has its own instance variable val = 20.

7) print(A.val, a1.val, a2.val)

A.val → accesses the class variable, still 5.

a1.val → accesses a1’s instance variable, which is 10.

a2.val → accesses a2’s instance variable, which is 20.

Final Output
5 10 20

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (118) AI (152) Android (25) AngularJS (1) Api (6) Assembly Language (2) aws (27) Azure (8) BI (10) Books (251) Bootcamp (1) C (78) C# (12) C++ (83) Course (84) Coursera (298) Cybersecurity (28) Data Analysis (24) Data Analytics (16) data management (15) Data Science (217) Data Strucures (13) Deep Learning (68) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (17) Finance (9) flask (3) flutter (1) FPL (17) Generative AI (47) Git (6) Google (47) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (186) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (11) PHP (20) Projects (32) Python (1218) Python Coding Challenge (884) Python Quiz (342) Python Tips (5) Questions (2) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (45) Udemy (17) UX Research (1) web application (11) Web development (7) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)