sturgemeister
sturgemeister

Reputation: 456

Is there any use for a python property getter?

I'm wondering if there is any use for explicitly using the getter decorator for class properties:

class A:
    @property
    def p(self):
       return self._p

    @p.setter
    def p(self, val):
       assert p < 1000
       self._p = val

    @p.getter
    def p(self):
       return self._p

why would I ever explicitly use the getter here? Doesn't it render the code within p(self) unreachable? Basically, is there any practical reason to use it?

Upvotes: 5

Views: 113

Answers (1)

Aran-Fey
Aran-Fey

Reputation: 43276

It's useful when you inherit a property from a parent class and want to override the getter:

class Parent:
    @property
    def prop(self):
        return 'Parent'

    @prop.setter
    def prop(self, value):
        print('prop is now', value)


class Child(Parent):
    @Parent.prop.getter
    def prop(self):
        return 'Child'

This creates a copy of Foo.prop with a different getter function but the same setter (and deleter).

Upvotes: 4

Related Questions