Bird
0
0

How can you use a class method to create an alternative constructor that creates an object from a string?

hard📝 Application Q15 of 15
Python - Class Methods and Static Methods
How can you use a class method to create an alternative constructor that creates an object from a string?
Example: Person.from_string('John-25') creates Person('John', 25).
Which code snippet correctly implements this?
Aclass Person: def __init__(self, name, age): self.name = name self.age = age @staticmethod def from_string(data): name, age = data.split('-') return cls(name, int(age))
Bclass Person: def __init__(self, name, age): self.name = name self.age = age def from_string(self, data): name, age = self.split('-') return Person(name, int(age))
Cclass Person: def __init__(self, name, age): self.name = name self.age = age @classmethod def from_string(cls, data): name, age = data.split('-') return cls(name, int(age))
Dclass Person: def __init__(self, name, age): self.name = name self.age = age @classmethod def from_string(self, data): name, age = data.split('-') return cls(name, int(age))
Step-by-Step Solution
Solution:
  1. Step 1: Recognize the use of class method as alternative constructor

    The method should be decorated with @classmethod and take cls as first parameter.
  2. Step 2: Parse string and return new instance

    Split the string, convert age to int, and return cls(name, int(age)) to create a new object.
  3. Final Answer:

    @classmethod with cls parameter returning cls instance -> Option C
  4. Quick Check:

    Alternative constructor = @classmethod + cls + return cls(...) [OK]
Quick Trick: Use @classmethod and cls to build alternative constructors [OK]
Common Mistakes:
  • Using @staticmethod instead of @classmethod
  • Missing cls parameter or using self
  • Not returning cls instance

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes