Bird
0
0

You want to create a class method that returns a new instance of the class with default values. Which of these implementations is correct?

hard📝 Application Q8 of 15
Python - Class Methods and Static Methods
You want to create a class method that returns a new instance of the class with default values. Which of these implementations is correct?
class User:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def default_user(cls):
        return cls("Guest", 0)
AThe method should use self instead of cls to create the instance.
BThe method correctly returns a new User instance with default values.
CThe method should be a static method, not a class method.
DThe method is missing a return statement.
Step-by-Step Solution
Solution:
  1. Step 1: Understand purpose of class method

    Class methods can be used as alternative constructors to create instances with default or custom values.
  2. Step 2: Check method implementation

    The method uses cls to call the constructor with default arguments and returns the new instance.
  3. Final Answer:

    The method correctly returns a new User instance with default values. -> Option B
  4. Quick Check:

    Use cls() in classmethods to create new instances [OK]
Quick Trick: Use cls() inside classmethods to create new instances [OK]
Common Mistakes:
  • Using self instead of cls
  • Forgetting to return the new instance
  • Confusing static and class methods

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes