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:
Step 1: Recognize the use of class method as alternative constructor
The method should be decorated with @classmethod and take cls as first parameter.
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.
Final Answer:
@classmethod with cls parameter returning cls instance -> Option C
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
Master "Class Methods and Static Methods" in Python
9 interactive learning modes - each teaches the same concept differently