Bird
0
0

Find the error in this code snippet:

medium📝 Debug Q6 of 15
Python - Class Methods and Static Methods
Find the error in this code snippet:
class Person:
    def __init__(self, name):
        self.name = name

    @classmethod
    def greet(cls):
        print(f"Hello, {name}!")

Person.greet()
AMissing self parameter in greet method
BCannot call class method without instance
CMissing @staticmethod decorator
DUsing undefined variable 'name' inside class method
Step-by-Step Solution
Solution:
  1. Step 1: Analyze class method greet

    greet is a class method and does not have access to instance variables like name.
  2. Step 2: Identify variable usage

    The variable 'name' is not defined inside greet, causing a NameError.
  3. Final Answer:

    Using undefined variable 'name' inside class method -> Option D
  4. Quick Check:

    Class methods can't access instance variables directly = B [OK]
Quick Trick: Class methods can't use instance variables without instance [OK]
Common Mistakes:
  • Assuming class methods can access instance variables
  • Confusing self and cls usage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes