Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any use for a python property getter?

Tags:

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?

like image 736
sturgemeister Avatar asked Sep 12 '19 20:09

sturgemeister


1 Answers

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).

like image 96
Aran-Fey Avatar answered Sep 28 '22 19:09

Aran-Fey