Lesson explanation
After this lesson, you will be able to:
__init__.An instance attribute is stored on one object, usually assigned in __init__ as self.name = name. A class attribute is written in the class body and is shared as a default by every instance of that class:
class Worker:
region = "eu"
def __init__(self, name):
self.name = nameWorker.region reads the class setting. worker.region also reads it until that particular object has its own region attribute. If you assign worker.region = "us", that object now shadows the class setting; it does not update the other workers.
For genuinely shared configuration, update Worker.region (the class), not one instance. For per-object state such as a worker's name, retries, or event history, use self.attribute inside __init__.
Important mutable-state pitfall: a list defined in the class body can be shared by all instances. If each instance needs its own list, create self.events = [] in the constructor.
class ApiClient:
scheme = "https"
def __init__(self, service):
self.service = service
first = ApiClient("users")
second = ApiClient("billing")
print(f"{first.service}: {first.scheme}")
print(f"{second.service}: {second.scheme}")Output:
users: https
billing: httpsBoth objects read the same class setting while keeping their own service names.
class Job:
mode = "safe"
first = Job()
second = Job()
Job.mode = "fast"
print(first.mode)
print(second.mode)Output:
fast
fastNo instance defines its own mode, so both still read the class attribute.
class Storage:
tier = "standard"
primary = Storage()
backup = Storage()
primary.tier = "premium"
print(primary.tier)
print(backup.tier)
print(Storage.tier)Output:
premium
standard
standardprimary.tier became an instance attribute; the shared class default was unchanged.
class Monitor:
def __init__(self, name):
self.name = name
self.events = []
def record(self, event):
self.events.append(event)
api = Monitor("api")
queue = Monitor("queue")
api.record("started")
print(api.events)
print(queue.events)Output:
['started']
[]Each constructor call creates a fresh list for one monitor.
| Situation | Where to assign |
|---|---|
| Shared default or setting | In the class body: mode = "safe" |
| Change shared setting | Worker.mode = "fast" |
| Per-object state | In __init__: self.name = name |
| Override a shared default for one instance | worker.mode = "custom" |
| Per-object mutable list | In __init__: self.events = [] |
obj.setting = value does not change ClassName.setting; it creates or updates an instance attribute.self.name in the class body is not how instance initialization works; use __init__.