Alternative constructor

Report a typo

Below we have the Person class, which we use to store general information about the users. As for now, we have defined only the __init__ method with name and email as parameters.

class Person:
    
    def __init__(self, name, email):
        self.name = name
        self.email = email

Let's say we have a number of strings where a person's name and their email are separated by a single hyphen. Write a from_string method that will serve as an alternative constructor for the class and specify the name of the decorator above it. Use the split(some_separator) method to divide a string.

For example, given input "[email protected]", we should be able to create a user instance with the following specific values:

print(user.name)   # Test
print(user.email)  # [email protected]

You do not need to take any input or create new class instances yourself, just write the body of the method.

Write a program in Python 3
class Person:

def __init__(self, name, email):
self.name = name
self.email = email

# use appropriate decorator
def from_string(...):
...
___

Create a free account to access the full topic