Class Methods in Python
Use @classmethod to create alternative constructors.
IntermediateObject-Oriented ProgramsExample 13 of 25
class-methods.py
Run in browser1# Program to demonstrate class methods23class Employee:4 def __init__(self, name, salary):5 self.name = name6 self.salary = salary78 @classmethod9 def from_string(cls, data):10 name, salary = data.split("-")11 return cls(name, float(salary))1213e = Employee.from_string("Alice-75000")14print(e.name, e.salary)
Output
Alice 75000.0
What's going on
The class method 'from_string' constructs Employee objects from a string representation.