I trip over this in our code at work all the time.

Python has this concept of “properties”:

class Oink:
    def __init__(self):
        self._foo = 3

    @property
    def my_property(self):
        return self._foo


a = Oink()
print(a.my_property)

my_property() is a method but it can be used as if it were a field.

This can also be used to define a setter:

class Oink:
    def __init__(self):
        self._foo = 3

    @property
    def my_property(self):
        return self._foo

    @my_property.setter
    def my_property(self, value):
        self._foo = 123 * value

Because, for some reason, Python people don’t like getters and setters. Instead, they hide it behind a property.

The result is, when you read this:

a.my_property = 5
print(a.my_property)

You have no idea that this actually calls a method.

⤋ Read More