Sub topic 5
Your first property: the getter
This chapter shows how to turn a method into something callers read like a plain attribute. It covers the @property decorator, what Python does when you read the attribute, and the mistakes people most often make with a first getter.
It assumes you can define classes and methods, set instance attributes in __init__, use the @ decorator syntax, and raise and catch exceptions. Earlier chapters covered the leading underscore convention. This chapter relies on it.
The problem a getter solves
Python code usually starts with plain attributes:
class Product:
def __init__(self, name, price):
self.name = name
self.price = priceCallers write product.price. Suppose you later decide to store prices as integer cents to avoid floating-point rounding. If price is a plain attribute, you have two bad options. You can change the meaning of price and break every caller. Or you can add get_price() and break every caller anyway.
A property avoids both. You keep the name price, change the storage underneath, and every product.price expression keeps working.
Your first property
A property is a method that Python runs when you read an attribute with the same name. You create one by decorating a method with @property:
class Product:
def __init__(self, name, price_cents):
self.name = name
self._price_cents = price_cents
@property
def price(self):
"""Price in dollars."""
return self._price_cents / 100
p = Product("notebook", 1250)
print(p.price) # 12.5Points to notice:
- The method takes only
self. A getter receives no other arguments. - The caller writes
p.price, with no parentheses. - The data lives in
_price_cents. The leading underscore tells readers that the attribute is internal and thatpriceis the public name. - The property reads like an attribute but runs code on each read.
What happens when you read it
When you write p.price, Python looks up price on the type of p before it looks in the instance's __dict__. It finds a property object on the class and calls the function you decorated.
This is why the getter runs every time. Nothing is stored under the name price on the instance. If the getter does heavy work, each read pays for it. The cached_property chapter covers that case.
You can see the property object by reading the name from the class instead of from an instance:
class Product:
def __init__(self, name, price_cents):
self.name = name
self._price_cents = price_cents
@property
def price(self):
"""Price in dollars."""
return self._price_cents / 100
print(type(Product.price).__name__) # property
print(Product.price.__doc__) # Price in dollars.The getter's docstring becomes the property's docstring, so help(Product) shows it. Put the description on the getter and nowhere else.
A getter can compute its value
The getter does not have to return a stored value. It can build the value from other attributes, which keeps the derived value from going stale:
class Person:
def __init__(self, first, last):
self.first = first
self.last = last
@property
def full_name(self):
return f"{self.first} {self.last}"
person = Person("Ada", "Lovelace")
print(person.full_name) # Ada Lovelace
person.last = "King"
print(person.full_name) # Ada KingIf you had stored full_name in __init__, the second print would still show the old name. A later chapter treats computed properties in full.
Common errors
Calling the property with parentheses
A property returns its value, not a method. Adding () calls the returned value:
class Product:
def __init__(self, price_cents):
self._price_cents = price_cents
@property
def price(self):
return self._price_cents / 100
p = Product(1250)
try:
p.price()
except TypeError as exc:
print(exc) # 'float' object is not callableThe message names the type of the returned value, not the property. When you see "object is not callable" on something you meant to define as a property, look for stray parentheses.
Using the same name for the property and the storage
The property is named price. If the getter reads self.price, it triggers itself:
class Broken:
def __init__(self):
self._value = 1
@property
def value(self):
return self.value # reads the property again
try:
Broken().value
except RecursionError:
print("getter called itself until the stack ran out")Store the data under a different name, by convention the public name with one leading underscore. The same rule applies to setters, where it causes the same failure when __init__ or the setter assigns to the public name incorrectly.
Assigning to a getter-only property
A property with only a getter is read-only. Assigning to it fails:
class Product:
def __init__(self, price_cents):
self._price_cents = price_cents
@property
def price(self):
return self._price_cents / 100
p = Product(1250)
try:
p.price = 20
except AttributeError as exc:
print(exc) # message varies by Python version; it says the property has no setterThe exact wording differs between Python versions, but the exception type is AttributeError. The next chapters use this behavior deliberately and show how to add a setter.
Expecting an instance attribute to override it
A property is found on the class, and it wins over an instance attribute of the same name. This matters only if you try to bypass the property by writing to __dict__ directly, which you should not do. Reading goes through the getter regardless.
Hiding bugs behind AttributeError
If code inside a getter raises AttributeError, for example from a typo like self._price_cent, the error message points at the getter's line. This is usually easy to diagnose. It becomes confusing only when the class also defines __getattr__. Python then treats the failure as "attribute missing" and calls __getattr__, which can hide the real cause. If you combine the two, test the getter by itself.
When to use a getter
Use a getter when the public name should stay stable while the implementation can change. Typical reasons:
- You need to expose a value derived from other attributes.
- You want to rename or restructure internal storage without breaking callers.
- You want a value that callers cannot assign to.
Do not use a getter that only returns an attribute of the same meaning with no extra behavior. Such a getter adds code and a function call to every read. A plain attribute can be converted to a property later without changing any caller, so there is no need to add one in advance.
The getter should also behave like an attribute. Callers expect p.price to be cheap, free of side effects, and consistent between two reads in a row. If reading it sends a network request or modifies state, make it a method with a verb name such as fetch_price().
Summary of the working model
| Item | Behavior |
|---|---|
| Definition | `@property` above a method that takes only `self` |
| Access | `obj.name`, with no parentheses |
| Where it lives | On the class, as a `property` object |
| When it runs | Every read of the attribute |
| Storage | A separate internal name such as `_name` |
| Assignment | Fails with `AttributeError` unless a setter exists |
Exercise
A class defines @property def area(self): return self.area. What happens when you read shape.area, and how do you fix it?
Show answer
The getter reads self.area, which is the property itself, so it calls the getter again and recurses until Python raises RecursionError. Fix it by computing the value from other attributes (for example self.width * self.height) or by returning a differently named stored attribute such as self._area.
Exercise
A Temperature class has a property kelvin defined with @property. A teammate writes t.kelvin() and gets TypeError: 'float' object is not callable. Explain the cause and give the corrected call.
Show answer
Reading t.kelvin already runs the getter and returns a float. The trailing () tries to call that float. The correct expression is t.kelvin, with no parentheses.