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

@movq@www.uninformativ.de The nice thing about properties is that you can compute and cache things on the fly at first attempt and also ensure validation for writing. But like you said, since it’s not obvious that reading or writing might do some more things, it’s strongly advised to avoid doing expensive stuff disguised as properties.

I reckon the vast majority of property use cases is to provide read-only access. At least that was my impression when I was doing a lot more in Python.

Personally, I think that this just reads a lot nicer:

oink.my_property
oink.my_property = 42

Than:

oink.get_my_property()
oink.set_my_property(42)

Btw, any field access is implemented using method calls. I might be wrong, but I believe there’s always __getattr__ and __setattr__ involved. 8-)

⤋ Read More

Participate

Login or Register to join in on this yarn.