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.
- A trader sold a product for Rs. 180 after allowing a discount of ‘z%’ on its marked price. If the marked price of the product is Rs. 200, then find the...
‘A’ invested Rs. 6600 for ‘x’ months while ‘B’ invested Rs. 1100 less amount than ‘A’ for (x + 3) months...
An item is sold with a 20% loss. If the cost price is reduced by Rs. 8 and the selling price is raised by Rs. 20, a profit of 20%...
Marked price of an article is Rs.1250 more than the cost price. When the same article is sold at a discount of Rs.500, the profit percent earned is 25%....
A dealer buys three types of mangoes at Rs. 40, Rs. 30 and Rs. 10 kg respectively. He mixes them in the ratio of 2:3:4 by weight and sells them at a pro...
- The cost price, selling price and marked price of an appliance are in the ratio 5:7:11. If the profit made is Rs. 600, then how much discount was offered o...
A shopkeeper sets the marked price of an item at 50% higher than its cost price. He then offers two successive discounts of 20% and m% on the marked pri...
Vikram started a business with a capital of ₹3000. After 5 months, Meera joined him with a capital which is 25% more than Vikram’s capital. At the e...
Tickets numbered 1 to 40 are mixed up and then a ticket drawn at random. What is the probability that the ticket drawn bears a number which is multipl...
A trader sells two chains for Rs. 4100 each, neither losing nor gaining in all. If he sold one of the chains at a gain of 25%, the other was sold at a ...