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 attributes

face Josiah Wang

So far, you have mainly implemented instance attributes, where you can access attributes via self inside the class definition or via an instance of the class from outside the definition.

1
2
3
4
5
6
7
class Person:
    def __init__(self, name, age):
        self.name = name      # instance attribute
        self.age = age        # instance attribute

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

You can actually also define a class attribute. Here, the attribute belongs to the class (e.g. Person) and not to the class instance (e.g. the object lecturer refers to).

The attribute is bound to the class, and not to the instance. The value is shared among all instances of the class.

You can access a class attribute either with ClassName.attribute or instance_name.attribute. It is probably easier to illustrate this with an example.

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

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

lecturer = Person("Josiah", 20)
print(Person.count) # 1
print(lecturer.count) # 1

assistant = Person("Luca", 18)
print(Person.count) # 2
print(lecturer.count) # 2
print(assistant.count) # 2

In this example, Person.count acts as a ‘global’ counter that keeps track of how many instances of Person have been created.

You can see how count is bound to Person, rather than to the instances (although you can still access it via the instance).

Class attributes are also useful if you want to define a constant, for example Person.SPECIES.