What is a class attribute in Python? How to access it?
Let’s look at an example:
In the above example,
data is the class attribute of
start is the instance
attribute which gets created when an instance of that class is created.
To access the class attribute, use the class name followed by a dot and then attribute name:
However, watch out:
What’s going on? Is there an instance attribute named
DummyClass? No, but the
value of class attribute
data is returned. This has something to do with
namespace resolution in python. Due to this characteristic, you should
be fully aware of the semantics of class attributes to read and modify them correctly. For
more details, please read this blog post; the details are not the
main focus of this post. This post talks about when to use class attributes.
From the above example, it is clear that class attribute value can be retrieved even by class instance, which is not what class attribute is designed for. So, what for then?
- Storing constants - class-wide, class-specific constants. This usecase is a very common usecase for class attributes.
That’s it! Here is some example.
After talking about class/instance attributes, let’s turn our attention to methods in a class. What methods have access to class/instance attributes, and how they reference those attributes?
Instance variables/attributes are only accessible through instance methods, meaning that they
are object-state dependent methods and are bound to instances of a class. These methods
refer to instance attributes by using
self instance object.
staticmethod is a special kind of methods that doesn’t use the object itself at all. In
other words, it doesn’t have access to instance nor class attributes. But these methods are
still bound to a Class object that contains this
classmethod is the kind of methods that have access to class attributes.
usually have a reference
cls as its first argument, which is a reference to the Class
object that contains this
When to use
- Factory methods - and this is actually the most common usecase.
- Static methods calling static methods - see example.
The second usage has the following reason behind it:
if you split a static methods in several static methods, you shouldn’t hard-code the class name but use class methods. Using this way to declare our method, the class name is never directly referenced and inheritance and method overriding will work flawlessly.