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.
рдирд┐рдореНрдирд▓рд┐рдЦрд┐рдд рдкреНрд░рд╢реНрди рдореЗрдВ , рджрд┐рдП рдЧрдП рдЪрд╛рд░ рд╡рд┐рдХрд▓реНрдкреЛрдВ рдореЗрдВ рд╕реЗ , рдЙрд╕ рд╡рд┐рдХя┐╜...
рдирд┐рдореНрдирдирд▓рд┐рдЦрд┐рдд рдкреНрд░рд╢реНрди рдореЗрдВ рдХреМрдирд╕рд╛ рд╡рд┐рдХрд▓реНрдк рд╕рд╣реА рдирд╣реАрдВ рд╣реИ ?
рдирд┐рдореНрдирд▓рд┐рдЦрд┐рдд рд╡рд╛рдХреНрдпреЛрдВ рдХреЗ рд░рд┐рдХреНрдд рд╕реНрдерд╛рди рдкрд░ рдЙрд╕рдХреЗ рдиреАрдЪреЗ рджрд┐рдП рдЧрдП ...
рдирд┐рдореНрдирд▓рд┐рдЦрд┐рдд рд╢рдмреНрджреЛрдВ рдореЗрдВ рд╕реЗ рдЕрддрд┐рдХрд░┬а рдХрд╛ рд╕рд╣реА рдкрд░реНрдпрд╛рдп рд╣реИ ?
"рдЦреЗрд▓ рдЦрддреНрдо, рдкреИрд╕рд╛ рд╣рдЬрдо" рдХрд╛ рдЕрд░реНрде рд╣реИ:
рдирд┐рдореНрдирд▓рд┐рдЦрд┐рдд рдореЗрдВ рд╕реЗ ' рд╡рд┐рдЪрд┐рддреНрд░ ' рдХрд╛ рдкрд░реНрдпрд╛рдпрд╡рд╛рдЪреА рдХреНрдпрд╛ рд╣реЛрдЧрд╛ ?
рдирд┐рдореНрдирд▓рд┐рдЦрд┐рдд рдкреНрд░рддреНрдпреЗрдХ рдкреНрд░рд╢реНрди рдореЗрдВ рджрд┐рдП рдЧрдП рд╢рдмреНрдж рдХреЗ рд╕рдорд╛рдирд╛рд░я┐╜...
рднрд╛рд░рдд рд╕рд░рдХрд╛рд░ рдиреЗ рд╣рд┐рдиреНрджреА рдХреЛ рд░рд╛рдЬрднрд╛рд╖рд╛ рдХреЗ рд░реВрдк рдореЗрдВ рдХрдм рд╕реНрд╡реАрдХрд╛рд░ я┐╜...
тАШрд╕реНрдиреЗрд╣тАЩ рд╢рдмреНрдж рдХрд╛ рдкрд░реНрдпрд╛рдпрд╡рд╛рдЪреА рдирд╣реАрдВ рд╣реИ:
рдореБрд╣рд╛рд╡рд░рд╛ тАЬрдЖрдБрдЦ рджрд┐рдЦрд╛рдирд╛тАЭ рдХрд╛ рд╕рд╣реА рдЕрд░реНрде рд╣реИ тАФ