Question
Consider the following Python code snippet: class
Employee: def __init__(self, name, age): self.name = name self.age = age def display(self): print(f"Name: {self.name}, Age: {self.age}") e1 = Employee("John", 30) e1.salary = 50000 e1.display() print(e1.salary) What will happen when the above code is executed?Solution
The code demonstrates Python's ability to dynamically add attributes to an instance of a class. 1. Instance Attributes: While name and age are initialized in the __init__ method, the salary attribute is added dynamically to the e1 instance after the object is created. Python allows this flexibility without any compile-time errors. 2. Output Explanation: When e1.display() is called, the display method prints name and age. Then, e1.salary is accessed and printed directly. 3. Execution Result: The code will output: Name: John, Age: 30 50000 This behavior demonstrates Python's dynamic nature and object-oriented principles. Why Other Options Are Incorrect: • A) It will print the name, age, and salary of the employee: The display method does not include salary, so salary is not printed there. • B) It will raise an AttributeError when accessing e1.salary: Python allows adding attributes dynamically; no error occurs. • D) It will execute but not print the salary attribute: e1.salary is explicitly printed in the last line. • E) It will fail to execute due to missing method to initialize salary: There is no requirement for salary to be initialized in the __init__ method.
The Performance Grading Index for Districts (PGI-D) is released by which of the following institutions?
Which of the following films was the best film of the year 2020 in 45th Bangladesh National Film Awards 2020?
Which ministry has launched the Swachh Survekshan Grameen (SSG) 2025?
How much dividend did the RBI transfer to the central government, contributing to lower fiscal deficit?
On which date was NSDL Payments Bank included in the Second Schedule of the RBI Act, 1934?
In which city were the first-ever methanol-powered buses introduced by Nitin Gadkari?
______ has sold its 14.50% stake in its subsidiary through an IPO.
Who has recently released the 'National Multidimensional Poverty Index'?
In which country the Prime Minister Shri Narendra Modi has received the 'World Peace Award'?
The simple interest received on a certain sum is Rs.1782 for 3 years. What will be the simple interest on the same sum at the same rate of interest for ...