Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Using attributes on classes PREMIUM

Series: Classes
Trey Hunner smiling in a t-shirt against a yellow wall
Trey Hunner
3 min. read Watch as video Python 3.9—3.13
Python Morsels
Watch as video
03:00

When are class attributes used in Python?

An example class attribute

Python's classes can have attributes, the same way that instances of classes can have attributes.

For example, here's a dataclass with a color attribute:

>>> from dataclasses import dataclass
>>> @dataclass
... class Point:
...     x: float
...     y: float
...     z: float
...     color: str = "purple"
...

This class's color attribute is set to the string purple:

>>> Point.color
'purple'

When are class attributes typically used?

Class creation helpers

This Point dataclass has an attribute called color. But we don't actually care about the attribute itself; what we care about is how the dataclass decorator used that attribute.

When we make a new Point object, if we don't specify a color argument, we'll end up with the default value that we originally defined on the class:

>>> p = Point(1, 2, 3)
>>> p.color
'purple'

We can even delete that attribute from our class, and that default value will remain, even on new instances of our class:

>>> del Point.color
>>> p.color
'purple'
>>> q = Point(1, 2, 3)
>>> q.color
'purple'

We only defined that attribute to tell the dataclass decorator what it should do when creating our class's initializer method.

These sorts of class attributes are essentially class creation helpers. They signal something useful to a decorator, or a parent class, or a metaclass.

Constant data

Another common use for class attributes are constant values.

For example, Django's AppConfig class uses specific constants that can be defined on the class:

from django.apps import AppConfig


class UsersConfig(AppConfig):
    name = "users"
    verbose_name = "Accounts"

Constants that are very related to a class often live on that class.

This data is shared between all instances of this class. Child classes, like our UsersConfig class, are able to override that data by setting their own class attributes with the same name.

Note that if data shouldn't actually be changed on child classes, that data might be better stored at the module level, instead of on a class:

from django.apps import AppConfig

name = "users"

class UsersConfig(AppConfig):
    verbose_name = "Accounts"

Shared state

Shared state is another possible use for class attributes.

Class attributes inherently share state between all instances of a class.

This class keeps track of the number of instances of it that exist in memory:

class Record:

    num_records = 0

    def __init__(self, data):
        self.data = data
        Record.num_records += 1

    def __del__(self):
        Record.num_records -= 1

So right now, this num_records attribute is 0:

>>> Record.num_records
0

But if we create a new instance of this Record class, we'll see that num_records becomes 1:

>>> gertrude = Record({'name': 'Gertrude', 'room': 230})
>>> Record.num_records
1

And if we create two more Record objects, we'll see that num_records becomes 3:

>>> david = Record({'name': 'David', 'room': 125})
>>> marcy = Record({'name': 'Marcy', 'room': 340})
>>> Record.num_records
3

Class attributes should be used for a state that should be updated on every instance of a class, not just on one instance. Although, this is honestly pretty uncommon.

It's unusual to see classes that use shared state that changes over time.

Be cautious with class attributes

Classes are objects in Python (everything is an object), and like all objects, they can have attributes.

It's pretty common to see class attributes used to store constant data on a class.

But you'll also sometimes see them used with class creation helpers, like the dataclass decorator.

But keep in mind that class attributes share state between all instances of a class. So it's somewhat uncommon to see class attributes that change after the class has been defined.

Python Morsels
Watch as video
03:00
This is a free preview of a premium screencast. You have 2 previews remaining.