liveBook · Manning

Accessor method

As explained in Software Design for Python Programmers

A getter method is a method that reads an object's state through a public access interface without exposing its underlying representation.

An accessor method lets client code read an object's state through a public interface without depending on the hidden representation. A getter may return a private instance variable today and obtain the same value from another source, such as a database, later. section 5.2

Use accessors to control how state is observed and changed:

  • Define a getter with @property so callers can write item.price rather than access item._price. section 5.2
  • Add a setter only when mutation is justified, and validate new values before changing hidden state. section 5.2 section 5.4
  • Avoid setters that update related fields independently when intermediate combinations can make the object invalid. section 5.5
  • Return copies from getters when the returned object is mutable and the enclosing object must remain immutable. section 5.7

A validated property

class Item: def __init__(self, price): self._price = price @property def price(self): return self._price @price.setter def price(self, new_price): assert new_price > 0 self._price = new_price item = Item(10.31) item.price = 10.75 # accepted item.price = -9.99 # AssertionError section 5.2

Listing 5.1 (Program 5.1 DemeterItem): item.py
class Item:
    def __init__(self, name, weight, price):
        self._name = name    #1
        self._weight = weight     #1
        self._price = price     #1

    @property
    def name(self): return self._name    #2

    @property
    def weight(self): return self._weight    #2

    @property
    def price(self): return self._price    #2

    @price.setter
    def price(self, new_price):    #3
        assert new_price > 0
        self._price = new_price

Inspect the complete Item implementation, including public properties, hidden fields, and the validating price setter. section 5.2

How Software Design for Python Programmers covers it

How deep it goes
Explains properties, validation, mutability hazards, lazy synchronization, and defensive copying through multiple worked examples.
Examples
Uses Item price properties, mutable Date Julian values, dangerous Date component setters, and Employee birthdate copies.
What you can do after
Build it from scratch with Python properties, validate mutations, preserve invariants, and prevent mutable state from leaking through getters.
How it connects
Connects accessors with encapsulation, information hiding, properties, validation, mutability, immutability, and lazy evaluation.

Also explained in

Compare how 13 books explain accessor method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Software Design for Python Programmers. The section links point to the parts of the book it draws on.