LearnFrenzy
Sign in Take a free test

OOP in Python · Predict the Output · Question 9

A classmethod alternative constructor Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

What is the output of the following Python program?

main.py
class Employee:
    raise_pct = 10

    def __init__(self, name, salary):
        self.name, self.salary = name, salary

    @classmethod
    def from_csv(cls, line):
        name, salary = line.split(",")
        return cls(name, int(salary))

    @classmethod
    def set_raise(cls, pct):
        cls.raise_pct = pct

e = Employee.from_csv("Asha,50000")
Employee.set_raise(15)
print(e.name, e.salary, e.raise_pct, type(e).__name__)
  • A Asha 50000 10 Employee
  • B Asha 50000 15 type
  • C Asha 50000 15 Employee Correct
  • D TypeError
Correct Answer: Option C

from_csv builds an Employee through cls; set_raise changes the class attribute that every instance reads.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links