Python language basics 77: class property getters
January 31, 2016 Leave a comment
In the previous post we looked at a special group of class level methods called setters. We saw that they were really not different from other class level methods. The single major difference lies in the purpose of setters, which is to let external users of a class provide a value for a class property. We also discussed that a setter may not be available for immutable, read-only or otherwise complex class properties.
In this post we’ll look at the counterpart of setters called getters.
Recall why setters are called setters: to set the value of a property. You can then guess the purpose of getters: to get the value of a property.
We said that it wasn’t wise to directly access a class level property like this:
person = Person("John", 100) print(person._name)
Here we’re only reading the value of “_name” but we’re still accessing it directly from the outside. Getters are designed to return the value of a class level property. Setters are normally void, i.e. do not return a value, but getters always return a value. Here’s the simplified Person class with getters and setters for the _name and _age properties:
class Person: def __init__(self, name, age): self._name = name self._age = age def get_name(self): return self._name def get_age(self): return self._age def set_name(self, name): self._name = name def set_age(self, age): self._age = age
Admittedly this is a solution influenced by Java and may well be rejected by hard core Python fans.
Here’s a lengthy discussion about getters and setters and properties in Python that you might want to read: Python 3 properties.
Here’s an example of using the above getters and setters:
person = Person("John", 100) person.set_name("Not John") print(person.get_name() + ", " + str(person.get_age()))
…which prints “Not John, 100”.
Read the next post here.
Read all Python-related posts on this blog here.