liveBook · Manning

Accessor method

As explained in Python How-To

An accessor method or function provides access to an object's property or state by retrieving its value, assigning a value, or defining behavior for such access.

In Python, a property getter retrieves a value, while a property setter controls what happens when a value is assigned. Use a setter when assignment needs checking, such as restricting a task’s status to allowed values. section 8.3.4

Listing 8.9 Creating a setter for a property
class Task:
    # __init__ stays the same
 
    @property
    def status(self):
        return self._status
 
    @status.setter
    def status(self, value):
        allowed_values = ["created", "started", "completed", "suspended"]
        if value in allowed_values:
            self._status = value
            print(f"task status set to {value}")
        else:
            print(f"invalid status: {value}")      #1

The Task example pairs a status getter with a setter that accepts four values and prints a message for an invalid value. section 8.3.4

Use accessor methods selectively:

  • Define a setter with @property_name.setter and check the assigned value before updating the internal attribute. section 8.3.4
  • Prefer direct attribute access and assignment unless a property is needed for read-only behavior or data verification; routine getters and setters add complexity. section 8.3.4 section 8.3.5

How Python How-To covers it

How deep it goes
Explains the setter decorator and value checking, then cautions against routine getter-and-setter wrappers.
Examples
Checks Task status against four allowed values and poses an urgency setter challenge for integers from 1 to 5.
What it assumes
Builds on Python classes and a read-only property, which are treated as prior knowledge rather than explained here.
What you can do after
Apply it by defining a property setter that checks assigned values before updating the internal attribute.
How it connects
Connects properties and getters with data integrity, encapsulation, and direct attribute access.

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 Python How-To. The section links point to the parts of the book it draws on.