Static methods and fields
medium 45 minA static member belongs to the class and not to one object.
Video lesson · Chapter 1 of 6
Make a prediction
Static methods and fields
1:02Reel
Theory
Read or listen first. About 2 min.
What it is
A static field belongs to the class. There is one, and all objects of the class share it. An instance field belongs to one object, and each object has its own.
A static method is called on the class and has no receiver: there is no this. It can use static members. It cannot use instance members unless somebody hands it an object.
Python splits the idea in two. A static method gets nothing. A class method gets the class as its first argument, so that it can create objects of the class it was called on, also of a subclass.
Why it exists
Some knowledge is about the kind and not about one thing: the value of pi, the number of sides of a die, how to read a date from text. Asking an object for it would be odd, and one would have to exist first.
Named constructors make creation readable. Temperature.of_celsius(20) says more than Temperature(20), may return a cached object, and may return a subclass.
The other side of the coin: a static field that changes can be reached from everywhere. It is simple to write and hard to test, hard to lock, and hard to have twice.
A short history
2001
Python 2.2 (21 December) brings staticmethod and classmethod, built on descriptors.
2003
PEP 318 is created on 5 June. It leads to the @ syntax for decorators in Python 2.4, so that @staticmethod stands above the method.
2021
JEP 395 is delivered with Java 16 and, among other things, lets inner classes declare static members.
Words to know
- Static field
- One value for the class. Also: class variable.
- Instance field
- One value for each object.
- Static method
- A function in the namespace of a class, without this.
- Class method
- Python: gets the class itself as the first argument.
- Static factory
- A static method that returns an object. A constructor with a name.
- Pure function
- Same input, same output, no effects. The best kind of static method.
- Global mutable state
- Something that changes and that everybody can reach.
- Static initializer
- Code that runs once when a class is initialized.
- Class loader
- Java's loader of classes. The same class in two loaders has two sets of static fields.
- Shadowing
- An object attribute with the name of a class attribute covers it.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
About whom?. The kind, or one thing of the kind
Understand it
Start here
The lid and the pawns
A board game comes in a box. Some things are printed or written on the lid, for everybody. Other things are written on a pawn, for one player.
On the lid: static. On the pawn: instance. The lid is handy, until people begin to write on it.
How it works
One copy or many
class Pawn: SIDES = 6 # constant, for all _out = 0 # one counter, for all def __init__(self, name): self.name = name # one per object Pawn._out += 1 @staticmethod def is_roll(n): # needs nothing of the class or an object return 1 <= n <= 6 @classmethod def out(cls): # needs the class return cls._out def greet(self): # needs one object return f"I am {self.name}, number {self._out} is the newest"print(Pawn.SIDES, Pawn.is_roll(7), Pawn.out())a, b = Pawn("A"), Pawn("N")print(a.name, b.name, Pawn.out(), a.out())try: Pawn.greet()except TypeError as error: print("no object:", error)Static and instance members
| Question | Static | Instance |
|---|---|---|
| Belongs to | The class | Each object |
| Copies | One, shared | One per object |
| Called by | Circle.square(5) | circle.area() |
| Can use | Static members only, or objects that it is given | Both |
this or self | None | The receiver |
| Lives | From class initialization to the end of the class, often of the program | As long as the object |
| Overridden? | No. Hidden (Java). Found by lookup on the class (Python) | Yes |
| Typical use | Constants, helpers, factories | Behaviour with state |
Underlined means static
1/3The class
Two static fields, three static methods. In UML they are underlined. Here they carry a note.
depends on
Two objects, one counter
Good uses
Four honest reasons
Helpers without state
Math.sqrt,Arrays.sort,Collections.reverse. They work on what they are given.Factory methods
Integer.valueOf,LocalDate.now,Optional.of. A constructor with a name.Constants
Math.PI,Integer.MAX_VALUE,Color.RED. Fixed and immutable.The one and only
Runtime.getRuntime(). One object, reached through the class. Weigh it against passing the object in: see Singleton.
Collections.reverse shows that a static method need not be pure: it changes the list that it is given. That is fine, because the caller handed the list over. The Singleton pattern has a page of its own, with its costs.
class Temperature: _cache = {} def __init__(self, kelvin): if kelvin < 0: raise ValueError("below absolute zero") self.kelvin = kelvin @classmethod def of_celsius(cls, c): return cls(round(c + 273.15, 2)) @classmethod def of_fahrenheit(cls, f): return cls.of_celsius((f - 32) * 5 / 9) def celsius(self): return round(self.kelvin - 273.15, 2)class Reading(Temperature): def label(self): return f"measured {self.celsius()} C"print(Temperature.of_fahrenheit(212).celsius())print(Reading.of_celsius(21).label()) # cls is Readingtry: Temperature.of_celsius(-300)except ValueError as error: print("refused:", error)With @staticmethod and a fixed Temperature(...) inside, Reading.of_celsius would return a Temperature without label. Use a class method for factories in Python. In Java a static factory names its class. When creation itself must vary, look at the Factory patterns.
Languages
The same word, small differences
| Language | Field for the class | Method without receiver | Worth knowing |
|---|---|---|---|
| Java | static int count | static | Can be called through an object, and compilers warn |
| C++ | inline static (C++17), before that defined once outside | static | Local statics are initialized once, safely, since C++11 |
| Python | Assigned in the class body | @staticmethod, @classmethod | self.x = ... covers the class attribute |
| JavaScript, TypeScript | static x, private static #x | static | Statics are inherited. this in a static method is the class |
| Kotlin | companion object, or top level | Same | The companion is a real object |
| Go | Package variable | Package function | No classes |
class Player: score = 0 friends = [] # one list for all!a, b = Player(), Player()a.friends.append("Noor")print("b has friends:", b.friends) # shared by accidenta.score += 1 # reads the class, writes the objectprint(a.score, b.score, Player.score) # 1 0 0Player.score = 10print(a.score, b.score) # 1 10: a is covered by its own attributeDanger
A static field that changes is a global
Bad: everybody reaches the same hidden state
1/3Handy
One call from anywhere: Ticket.take().
uses
Static or not?
Every order needs a number. Where does the counter live?
BreaksStatic int, ++ in the constructor
- How
number = next++.- Limit
- Two threads get the same number. Starts at 0 after every restart. Each server counts alone.
- Choose when
- A small script.
WorksA number object, passed in
- How
Numbers.take()with a lock. Created once at the start.- Limit
- Right inside one process. Not after a restart.
- Choose when
- One process, numbers only for this run.
StrongA number object backed by the database
- How
- Same interface, a sequence behind it.
- Limit
- A call over the network, and gaps after failures.
- Choose when
- Several processes or restarts. See Unique id generator.
Both sides
Helpers: function, static, or object?
A static helper is fine
- Depends on its arguments only
- One sensible implementation
- Nobody needs to replace it in a test
- It fits the class it stands in
Make it an object
- Reads the clock, random numbers, files or the network
- A second implementation is likely
- It remembers something between calls
- The class is called Utils and has 40 methods
static boolean isWeekend() { // hides a clock DayOfWeek d = LocalDate.now().getDayOfWeek(); return d == DayOfWeek.SATURDAY || d == DayOfWeek.SUNDAY;}static boolean isWeekend(LocalDate date) { // pure: still static, and honest DayOfWeek d = date.getDayOfWeek(); return d == DayOfWeek.SATURDAY || d == DayOfWeek.SUNDAY;}// isWeekend(LocalDate.now(clock)) in the program, any date in a testSummary
The whole topic in one minute.
Static: one per class, reached through the class, no this. Instance: one per object. A static method sees static members only, an instance method sees both.
Good: constants, pure helpers, static factories. Dangerous: static fields that change, hidden clocks and connections, utility classes that grow without end.
One per class really means one per class loader, per process, and in Python one per class object. Ten server processes have ten counters. If the number must be one for all, it belongs into a database.
- Static belongs to the class: one copy, no this.
- Static methods see static members, instance methods see both.
- Call them through the class name, not through an object.
- Good: constants, pure helpers, named constructors.
- A static field that changes is a global: locks, test order, hidden dependence.
- One per class loader, per process. Not one per system.