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
See it run
One copy or many: where a value lives, who sees a change, and how far one reaches.
Operations
The shared counter
The class exists before its objects.
Step 1 of 5
Class loaded
No circle yet. The class has its two fields, and can be asked.
Step 1: Class loaded
class Circle: PI = math.pi _count = 0 def __init__(self, name, radius): self.name, self.radius = name, radius Circle._count += 1 @classmethod def count(cls): return cls._countCircle.count()first = Circle("First", 2)second = Circle("Second", 3)Circle.count()- Good for
- Constants, counts for learning
- Costs
- One copy
- Copies of PI for 2 objects
- 1
Write the class name when you change a class attribute in Python.
In the real world
The same static methods and fields doing real jobs. Pick one and step through it.
Order numbers from a static field, in a service with two processes.
Step 1 of 5
Start
Both processes load the class. Each has its own static field.
Step 1: Start
Common mistakes
The bugs interviewers watch for, with the fix beside each.
A list on the class
criticalAll objects share one list.
Wrongclass Player: friends = []Rightclass Player: def __init__(self): self.friends = []this in a static method
minorThere is no instance. It does not compile in Java.
Wrongstatic void print() { System.out.println(this.name); }Rightstatic void print(Player p) { System.out.println(p.name); }Called through an object
minorIt looks as if the object mattered.
WrongMyClass obj = new MyClass();obj.staticMethod();RightMyClass.staticMethod();Lock on this for a static field
criticalTwo objects have two locks, the field is one.
Wrongsynchronized void hit() { count++; } // count is staticRightstatic synchronized void hit() { count++; }A hidden clock
majorNobody can test the last day of the year.
Wrongstatic boolean isWeekend() { ... LocalDate.now() ... }Rightstatic boolean isWeekend(LocalDate date) { ... }A cache without an end
majorA static collection keeps everything alive.
Wrongstatic Map<User, Session> all = new HashMap<>();Rightfinal class Sessions { /* limit and expiry */ }
Interview tips
One sentence
- This player: instance
- Every player: static
- Changes: an owner
Three good uses
- Constants
- Pure helpers
- Named constructors
Say the scope
- Thread, request
- Process, machine
- System
Move away slowly
- Static forwards to an object
- Callers move
- Close the door