Chapter 4: Class attributes and methods

Class methods

face Josiah Wang

A possible use case for class methods is to create new instances of the class using the Factory method. This is an OOP design pattern - you do not need to know the details!

Instead of creating a Person instance directly, you can use a method to create a Person, for example by their birth year. This can be a class method, since all you really need is the class name - this can be obtained from cls. You do not need anything from self! This saves you from having to create a new instance of Person just to use the create_from_birth_year() method.

from datetime import date

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

   @classmethod
   def create_from_birth_year(cls, name, birth_year):
      return cls(name, date.today().year - birth_year)

singer = Person.create_from_birth_year("Celine Dion", 1968)
print(singer.name) # Celine
print(singer.age) # 53