Bird
0
0

Find the error in this code snippet:

medium📝 Debug Q7 of 15
Python - Class Methods and Static Methods
Find the error in this code snippet:
class Animal:
    species = "Unknown"

    @classmethod
    def set_species(cls, species):
        species = species

Animal.set_species("Mammal")
print(Animal.species)
AMethod should be an instance method
BMissing @staticmethod decorator
CThe assignment inside set_species does not update class variable
Dspecies is a reserved keyword
Step-by-Step Solution
Solution:
  1. Step 1: Analyze assignment in class method

    The line 'species = species' assigns the parameter to itself, not to cls.species.
  2. Step 2: Identify correct assignment

    To update the class variable, it should be 'cls.species = species'.
  3. Final Answer:

    The assignment inside set_species does not update class variable -> Option C
  4. Quick Check:

    Assign to cls.variable to update class state [OK]
Quick Trick: Assign to cls.var to change class variables inside classmethods [OK]
Common Mistakes:
  • Assigning parameter to itself
  • Forgetting cls prefix for class variables
  • Confusing local and class scope

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes