Advanced Lesson 2
Advanced Object-Oriented Programming
Chapter 4: Class attributes and methods
Class attributes
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 |
|
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 |
|
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
.