Class Methods in Python

Use @classmethod to create alternative constructors.

IntermediateObject-Oriented ProgramsExample 13 of 25
class-methods.py
Run in browser
1# Program to demonstrate class methods
2
3class Employee:
4 def __init__(self, name, salary):
5 self.name = name
6 self.salary = salary
7
8 @classmethod
9 def from_string(cls, data):
10 name, salary = data.split("-")
11 return cls(name, float(salary))
12
13e = 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.