This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 4: Class attributes and methods

Class methods

face Josiah Wang

Like class attributes, you can also have class methods that are bound to the class (and not to the class instance).

A class method takes the class (cls) as its first argument, rather than the class instance (self) as in an instance method.

Thus, class methods do not have access to the object instance (via self), but only the class (via cls). Therefore, it does not have access to any instance attributes or methods.

Writing a class method is just like writing an instance method, except that you define cls instead of self as the first argument (PEP 8 recommends this convention). You will also need to annotate the method with a @classmethod decorator (Line 9). This decorator allows Python to know that cls is a class, and not an instance!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Person:
    count = 0

    def __init__(self, name, age):
        self.name = name
        self.age = age
        Person.count += 1

    @classmethod
    def get_population(cls):
        return f"Population: {cls.count}"

lecturer = Person("Josiah", 20)
print(Person.get_population())
print(lecturer.get_population())

Like class attributes, you can access a class method with either the ClassName (Line 14) or an instance_name (Line 15).

When Line 14 is executed, Python will pass Person as the first parameter cls. Therefore, cls.count (Line 11) is actually Person.count.

When Line 15 is executed, the same will happen. Python will figure out that lecturer is an instance of Person. Since get_population() is annotated as a class method, Python will pass the class name Person as the first parameter instead of the lecturer instance.

If you are from a C++/Java background: a class method in Python is actually equivalent to a static method in C++/Java. As we will see in a bit, a static method in Python is a completely different thing! Pure confusion! 😵😵😵