liveBook · Manning

Static field

As explained in The Well-Grounded Python Developer: How the pros use Python and Flask

A class variable is an attribute stored on a Python class and shared by its instances unless shadowed.

A static field—called a class-level variable in Python—lets instances share one value. That is useful when separate page requests need to see the same visit count. section 6.4.4

class PageVisit:
    COUNT = 0
 
    def counts(self):
        PageVisit.COUNT += 1
        return PageVisit.COUNT

PageVisit stores COUNT on the class. Each call to counts() increments that value and returns the new count, even when requests use different PageVisit instances. section 6.4.4

This counter works while one web server handles the requests. If multiple servers run, their class-level variables are not shared, so this approach cannot maintain one count across them. section 6.4.4

How The Well-Grounded Python Developer: How the pros use Python and Flask covers it

How deep it goes
Shows a working class-level counter and its single-server limit, without developing a multiple-server solution.
Examples
Uses PageVisit.COUNT and counts() to increment and display a page-visit counter.
What you can do after
Build it from scratch: implement a class-level page counter for requests handled by one server.
How it connects
Links Python classes and methods to web requests and Jinja2 template rendering.

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 The Well-Grounded Python Developer: How the pros use Python and Flask. The section links point to the parts of the book it draws on.