Python Class Attributes and Class Methods

28 Apr 2014

What is a class attribute in Python? How to access it?

Let’s look at an example:

class DummyClass(object):
    data = 1

    def __init__(self, arg1):
        self.start = arg1

In the above example, data is the class attribute of DummyClass and 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:

DummyClass.data
## 1

However, watch out:

a = DummyClass(2)
a.data
## 1

What’s going on? Is there an instance attribute named data for 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?

  1. 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 staticmethod.

classmethod is the kind of methods that have access to class attributes. classmethod usually have a reference cls as its first argument, which is a reference to the Class object that contains this classmethod.

When to use classmethods?

  1. Factory methods - and this is actually the most common usecase.
  2. 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.