Python Properties: Stored, Computed, Observers (didSet) & Lazy
Properties associate values with structures, classes, and enumerations. Learn Stored vs Computed properties, Property Observers (willSet and didSet) for responding to state changes, lazy stored properties for deferred initialization, and static type properties.
"A stored property is a physical storage shelf. A computed property is an electronic calculator on the wall that computes a value dynamically whenever you press the button. A property observer (didSet) is an alarm sensor that rings whenever a new package is placed on the shelf."
Deep Dive: How It Works
Computed Properties: var prop: Type { get { ... } set(newVal) { ... } } calculates a value dynamically rather than storing it.
Property Observers: didSet { ... } executes immediately after a new value is stored; willSet { ... } executes right before.
lazy Stored Properties: lazy var data = loadHugeFile() delays initialization until the property is first accessed.
Static Properties: static let maxLimit = 100 defines a type-level constant shared across all instances.
Syntax Blueprint
var score: Int = 0 {
didSet { print("Score changed from \(oldValue) to \(score)") }
}
var doubleScore: Int { score * 2 }Use didSet to monitor property mutations and var name: Type { ... } for computed getters.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Assigning to a property inside its own didSet observer without a guard condition.Why it happens: Can trigger recursive observer loops if not carefully managed.
How to fix: Avoid self-assignment in didSet or use computed getters.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Implement Step Counter with didSet
Define a struct StepTracker with var totalSteps: Int = 0.
Add a didSet observer to totalSteps that prints "Steps increased to \(totalSteps)".
In top-level code, create var tracker = StepTracker() and set tracker.totalSteps = 1000.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.