Class Methods in Python

Use @classmethod to create alternative constructors.

IntermediateObject-Oriented ProgramsExample 13 of 25
class-methods.py
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.

After this program

If the idea is still fuzzy, read Day 11: Classes and Objects in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 object-oriented programs, or see every topic on Python exercises.