Sub topic 1
Plain attributes and why direct access is the default
Prerequisites
This chapter assumes you can define a class with methods, you know how __init__ sets instance attributes, and you can read basic try/except code. You do not need to know decorators yet. Properties come in later chapters.
Instance attributes are just names
In Python, an instance attribute is a name stored on an object. You create it by assigning to it. There is no declaration step and no access keyword.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(3, 4)
print(p.x) # 3
p.x = 10
print(p.x) # 10
p.label = "origin" # a new attribute, added at runtime
print(p.label) # originEach instance keeps its attributes in a dictionary called __dict__. Reading p.x looks up "x" in that dictionary, after checking the class for anything that takes priority, such as a property.
print(p.__dict__) # {'x': 10, 'y': 4, 'label': 'origin'}Why direct access is the default
Languages such as Java often wrap every field in getX() and setX() methods. The reason is that changing a public field into a method later breaks every caller. Python avoids that problem. A plain attribute can later be replaced by a property with the same name, and callers keep writing obj.x. The change is invisible to them.
So the usual Python rule is: start with a plain attribute. Add control only when you need it.
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
item = Product("pen", 2.5)
item.price = 3.0
print(item.price * 4) # 12.0This code is short and easy to read. It has no boilerplate to maintain, and nothing in it is wrong yet.
What direct access cannot do
Plain attributes have limits. Python will accept any value you assign, so the class cannot protect its own rules.
item.price = -50
print(item.price) # -50
item.price = "free"
print(item.price) # freeNothing raised an error. The object is now in a state the author never intended. A later line such as item.price * 4 could return a surprising result or fail far from the real mistake.
The table below lists the needs that push you beyond a plain attribute.
| Need | Plain attribute | Later chapters |
|---|---|---|
| Reject invalid values | No check happens | Property setter |
| Forbid assignment | Anyone can assign | Read-only property |
| Derive a value from other data | You must keep it in sync by hand | Computed property |
| Run code when a value is read | Not possible | Property getter |
How the pieces fit together
Common mistakes
- Writing getters and setters up front. Methods like
get_price()add code and make callers writeitem.get_price()instead ofitem.price. If you later need control, a property gives you that without changing the public name. - Assuming a missing check is a bug in Python. Python trusts the programmer by design. Rules you want enforced are your class's job.
- Misspelling an attribute on assignment. Because assignment creates attributes,
item.prise = 3silently adds a new one. Readingitem.pricestill gives the old value.
item.prise = 3.5 # typo: creates a second attribute
print(item.price) # -50 (from earlier), not 3.5Exercises
Exercise
A class Timer has a plain attribute seconds. Existing code reads and assigns t.seconds in many places. Later you need to reject negative values. Why is this not a breaking change for callers if you plan to use a property?
Show answer
A property can use the same public name, seconds. Callers still write t.seconds to read and t.seconds = value to assign. Only the class internals change, so no caller code needs to be edited.
Exercise
After item = Product("pen", 2.5), you run item.prise = 3.0. What is item.price afterward, and why?
Show answer
It is still 2.5. Assigning to a name that does not exist creates a new attribute called prise on the instance. The original price attribute is untouched.