Is it possible to rewrite getter properties in a subclass?

For instance:

class Example:
    def __init__(self):
        self.v = 0

    @property
    def value(self):
        return self.v
    @value.setter
    def value(self, v):
        self.v = v

class SubExample(Example):
    pass

Is it possible to rewrite only the getter for a value in SubExample?

+3
source share
3 answers

You can do it like this:

class DoubleExample(Example):
    @Example.value.getter
    def value(self):
        return self.v * 2

o = Example()
o.value = 1
print o.value # prints "1"

p = DoubleExample()
p.value = 1
print p.value # prints "2"

However, this only works if it Exampleis a new style class ( class Example(object):), and not an old style class ( class Example:), as in your code example.


Warning. Thomas pointed out in the comments that this method may not meet expectations if you use multiple inheritance ( class Foo(Bar, Baz)).

+4
source

getter , no. - , , - , .

, , , , , :

class Example(object):
    def __init__(self):
        self.v = 0

    @property
    def v(self):
       return self._v_getter()
    @v.setter
    def v(self, value):
       return self._v_setter(value)

    def _v_setter(self, value):
        self._v = value

class SubExample(Example):
    def _v_getter(self):
        return 5

>>> se = SubExample()
>>> se.v
5
>>> se._v
0
>>> se.v = 10
>>> se.v
5
>>> se._v
10

, . , , .

+3

:

http://code.activestate.com/recipes/408713-late-binding-properties-allowing-subclasses-to-ove/ http://stackoverflow.com/questions/3393534/python-property-and-method-override-issue-why-subclass-property-still-calls-the

In fact, instead of using propertyit directly, you need to defer the call to the recipient so that he gets access to the one that was specified in the subclass, and not the one that is defined in the superclass when you first defined the property. This can be achieved with lambda:

class Test(object):
    def __init__(self):
        self.v = 0
    def _value(self):
        return self.v
    def _value_setter(self, v):
        self.v = v
    value = property(lambda self: self._value(), lambda self, v: self._value_setter(v))

class Test2(Test):
    def _value(self):
        return self.v + 1

a = Test()
a.value = 2
print a.value  # 2

b = Test2()
b.value = 2
print b.value  # 4
0
source

All Articles