liveBook · Manning

Static field

As explained in Python How-To

A class attribute is an attribute stored on a Python class and available to instances through attribute lookup when no instance-specific value overrides it.

In Python, a static field is usually called a class attribute: data defined on the class and shared by its instances. Use it when every instance should refer to the same value, rather than storing duplicate instance attributes. Place class attributes immediately below the class definition and above __init__ so their shared role is clear. section 8.1.4

class Task:
   user = "the logged in user"
 
   def __init__(self, title, desc, urgency):
       pass

Store the logged-in user once on Task instead of accepting and storing it separately for every task instance. section 8.1.4

Choose a class attribute when:

  • All instances share the same value, such as the user creating every task. section 8.1.4
  • A shared resource belongs to the class, such as a database connection used by Task operations. section 14.3.1
  • You need named constants, but recognize that ordinary class attributes do not create true enumeration members or support enumeration iteration. section 9.1.1 section 9.1.2

Shared task data

A Task class can expose a class-level user or database connection while keeping title, description, and urgency as per-instance attributes. For database-backed tasks, create_sqlite_database assigns the connection through cls.con and later operations reuse it. section 8.1.4 section 14.3.1

Listing 9.1 Implementing an enumeration class
from enum import Enum

class Direction(Enum):
   NORTH = 0
   SOUTH = 1
   EAST = 2
   WEST = 3

Use Enum when named constants should become discrete members rather than unrelated integer-valued class attributes. section 9.1.2

How Python How-To covers it

How deep it goes
Defines placement, memory rationale, and practical uses, but stops short of detailed attribute-lookup internals.
Examples
Uses shared task users, SQLite connections, and Direction constants to demonstrate appropriate and inappropriate class-attribute designs.
What it assumes
Assumes familiarity with Python classes and __init__, while contrasting shared class data with per-instance attributes.
What you can do after
Apply class attributes to reduce duplicated shared state and recognize when Enum is preferable for named constants.
How it connects
Connects class attributes with instance attributes, class methods, static methods, and enumeration classes.

Also explained in

Compare how 7 books explain static field →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.