Concept
Instance Attributes vs Class Attributes
Class attributes are shared across ALL instances. Instance attributes (attached to `self.x`) belong exclusively to that specific object.
python
class Dog:
species = "Canine" # Shared by every instance!
def __init__(self, name):
self.name = name # Unique to this instance!
d1 = Dog("Rex")
d2 = Dog("Bella")
print(d1.species, d2.species) # Canine Canine
# 118. Instance Attributes vs Class Attributes Class attributes are shared across ALL instances. Instance attributes (attached to `self.x`) belong exclusively to that specific object: ```python class Dog: species = "Canine" # Shared by every instance! def __init__(self, name): self.name = name # Unique to this instance! d1 = Dog("Rex") d2 = Dog("Bella") print(d1.species, d2.species) # Canine Canine ``` Trap: Never put a mutable list as a class attribute (`class Bank: ledger = []`). Every account created will share and corrupt that identical ledger list in memory.
Checkpoint
If you change a class attribute via `Dog.species = 'Wolf'`, who sees the change?
Practice
Create a class `Server` with a class attribute `status = "online"` and an instance attribute `port` in `__init__`. Instantiate `s = Server(8080)` and print `s.status`.
01
Tap code blocks below to assemble
Available Blocks