Sub topic 1
Plain Attributes and Why Direct Access Is the Default
Prerequisites
This chapter assumes you can:
- Define a class with methods and an
__init__method. - Create instances and read or assign attributes with dot notation.
- Read basic exceptions such as
AttributeError.
You don't need to know decorators yet. Properties come in later chapters. This chapter explains the plain attribute they build on, and why it is the right starting point.
The working model: attributes live in a dictionary
An instance attribute is a name stored on one object. In most classes, Python keeps these names in a dictionary called __dict__. Assigning obj.name = value adds or updates a key in that dictionary. Reading obj.name looks the key up.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1, 2)
print(p.__dict__) # {'x': 1, 'y': 2}
p.x = 10 # update an existing attribute
p.z = 5 # create a new one; no declaration needed
print(vars(p)) # {'x': 10, 'y': 2, 'z': 5}
del p.z # remove it again
print(hasattr(p, "z")) # Falsevars(p) returns the same dictionary as p.__dict__. Python has no attribute declarations. An attribute exists once something assigns it. Conventionally, __init__ assigns all of them, so a reader can see a class's data in one place.
Why direct access is the default
In languages such as Java, programmers often make every field private and write getX() and setX() methods. The reason is future flexibility. If validation is needed later, only the setter body changes, and callers stay the same.
Python gets the same flexibility another way. Callers write p.x, and p.x can later be turned into a property that runs code. The caller's syntax does not change. This idea is called the uniform access principle: reading a stored value and reading a computed value look the same to the caller.
Because of this, writing getters and setters up front buys nothing in Python. It costs you:
- More code to write and read.
p.set_x(p.get_x() + 1)is noisier thanp.x += 1. - Worse ergonomics. Augmented assignment, tuple unpacking into attributes, and tools that inspect attributes all work naturally with plain names.
- Speed. A method call is slower than a dictionary lookup.
The default rule is: start with a plain public attribute. Add control only when a real requirement appears, such as validation, a derived value, or a read-only guarantee.
How a read finds the attribute
When you write obj.name, Python searches in a fixed order. The simplified version for plain attributes is:
- The instance's
__dict__. - The class's
__dict__. - The base classes, in method resolution order.
If nothing matches, Python raises AttributeError. Properties are a special kind of class attribute that takes part in this search, and a later chapter covers exactly how. For now, this three-step model explains the behavior in the next section.
Instance attributes versus class attributes
A name assigned in the class body belongs to the class. A name assigned through self belongs to the instance. Reading finds the instance value first, so an instance can shadow a class value without changing it.
class Counter:
step = 1 # class attribute
def __init__(self):
self.value = 0 # instance attribute
a = Counter()
b = Counter()
a.step = 5 # creates an instance attribute on a only
print(a.step, b.step, Counter.step) # 5 1 1
print(a.__dict__) # {'value': 0, 'step': 5}Assignment through an instance never modifies the class attribute. It creates a new entry in that instance's dictionary. Reading is different: if the instance has no entry, the read falls through to the class.
Mutable class attributes are shared
Shadowing protects you from this problem with immutable values like numbers. A mutable class attribute is different, because you can mutate it without assigning to it.
class Basket:
items = [] # one list shared by every instance
def add(self, thing):
self.items.append(thing) # mutates the shared list
a = Basket()
b = Basket()
a.add("apple")
print(b.items) # ['apple']Nothing was assigned to b, yet b.items changed, because both instances read the same list from the class. The fix is to create the list per instance:
class Basket:
def __init__(self):
self.items = []
def add(self, thing):
self.items.append(thing)
a = Basket()
b = Basket()
a.add("apple")
print(b.items) # []Common errors with plain attributes
Typos silently create new attributes
Because assignment creates attributes freely, a misspelled name is not an error.
class Player:
def __init__(self):
self.health = 100
p = Player()
p.helth = 50 # typo: creates a second attribute
print(p.health) # 100
print(p.__dict__) # {'health': 100, 'helth': 50}The bug shows up later, as wrong behavior far from the typo. Linters and type checkers catch many of these. A class can also restrict its attribute names with __slots__, but that is a specialized tool and not a default. A property setter is another way to control assignment.
Aliasing: the attribute holds a reference
Assigning a mutable argument to an attribute stores a reference to the same object. It does not store a copy.
class Team:
def __init__(self, members):
self.members = members
names = ["ann"]
t = Team(names)
names.append("bob")
print(t.members) # ['ann', 'bob']If the class should own its data, copy it on the way in:
class Team:
def __init__(self, members):
self.members = list(members)This matters for encapsulation. Hiding an attribute behind a getter does not stop outside code from mutating a list the getter returns. Copying decides who owns the data. Name hiding does not.
Attributes that exist only sometimes
If __init__ assigns an attribute only in some branches, other methods can hit AttributeError depending on the path taken.
class Report:
def __init__(self, title, author=None):
self.title = title
if author:
self.author = author
r = Report("Q3")
try:
print(r.author)
except AttributeError:
print("author was never set")Assign every attribute in __init__, using None or another sentinel value when no real value exists. Every instance then has the same shape.
When direct access starts to hurt
Plain attributes stop being enough when you need one of these:
- Rejecting invalid values at assignment time.
- Making a value read-only after construction.
- Deriving a value from other attributes so it never goes stale.
- Running side effects, such as logging or invalidating a cache, when a value changes.
Each of these has a tool in the chapters that follow: naming conventions to signal internal state, then @property for validation, read-only access, and computed values. Until you have one of these needs, a plain attribute is the simpler and more Pythonic choice.
Summary of the working model
| Idea | What happens |
|---|---|
| `obj.x = v` | Stores `v` in `obj.__dict__["x"]`, creating or updating it |
| `obj.x` | Searches the instance, then the class, then base classes |
| Assignment through an instance | Never changes a class attribute; it shadows it |
| Mutable class attribute | Shared by all instances, unless you assign per instance |
| `self.attr = arg` | Stores a reference, not a copy |
Exercise
A class defines tags = [] in its body, and add_tag(self, t) does self.tags.append(t). Two instances a and b are created, then a.add_tag("x") runs. What does b.tags contain, and how do you fix the class?
Show answer
b.tags contains ["x"], because both instances read the same list stored on the class and append mutates it without assigning to either instance. Fix it by removing the class-level list and assigning self.tags = [] inside __init__, so each instance gets its own list.
Exercise
Given class Player: with __init__ that sets self.health = 100, what does this code print, and why?
p = Player()
p.helth = 50
print(p.health)
Show answer
It prints 100. The misspelled p.helth is not an error. Assignment creates a new attribute named helth in the instance's __dict__, and health is left unchanged.