Bird
Raised Fist0

Consider this code:

hard🚀 Application Q9 of Q15
Python - Class Methods and Static Methods
Consider this code:
class Logger:
    level = "INFO"

    @classmethod
    def set_level(cls, level):
        cls.level = level

    @classmethod
    def log(cls, message):
        print(f"[{cls.level}] {message}")

Logger.log("Start")
Logger.set_level("DEBUG")
Logger.log("Debugging")

What will be the output?
A[INFO] Start\n[INFO] Debugging
B[DEBUG] Start\n[DEBUG] Debugging
CError due to missing self
D[INFO] Start\n[DEBUG] Debugging
Step-by-Step Solution
Solution:
  1. Step 1: Trace initial log call

    Logger.level is initially "INFO", so first log prints [INFO] Start.
  2. Step 2: Update level and log again

    set_level changes Logger.level to "DEBUG", so second log prints [DEBUG] Debugging.
  3. Final Answer:

    [INFO] Start\n[DEBUG] Debugging -> Option D
  4. Quick Check:

    Class variable updated by classmethod affects all calls [OK]
Quick Trick: Class variables updated by classmethods affect all instances [OK]
Common Mistakes:
MISTAKES
  • Assuming level doesn't change after set_level
  • Confusing instance and class variables
  • Expecting error due to missing self

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes