Class Methods

Use @classmethod to create alternative constructors.

PythonIntermediate
Python
# Program to demonstrate class methods

class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    @classmethod
    def from_string(cls, data):
        name, salary = data.split("-")
        return cls(name, float(salary))


e = Employee.from_string("Alice-75000")
print(e.name, e.salary)

Output

Alice 75000.0

The class method 'from_string' constructs Employee objects from a string representation.