← index #2720PR #8881
Related · high · value 1.030
QUERY · ISSUE

Can't get property value of the superclass

openby nuphaopened 2016-12-25updated 2023-03-06
bug

As following code shows, a subclass to override property 'p' of superclass. Calling super().p in subclass will return a property object, not the value. Further more, this property object has no .fget attribute as suggested in standard python. But a 'getter' method is found on property object, when I call .getter(o), another property object returned, still not value.

So, I can't get the property value of superclass. Any suggestion?

class A:
@property
def p(self):
return {"a":10}

class AA(A):
@property
def p(self):
# get super property, add some new value
v = super().p
v['aa'] = 20 # this will raise an exception, because v is a property object, not a dict
return v

CANDIDATE · PULL REQUEST

objproperty.c: Add support for fget/fset/fdel.

closedby iabdalkaderopened 2022-07-07updated 2023-06-24
py-core

This patch allows a sub-class to override a property setter and call the base class's property setter. Without this, the workaround would be to access what should be a private attribute of the base class (f._bar), which is not a good practice. Tested with the following:

paste mode; Ctrl-C to cancel, Ctrl-D to finish
=== class Foo():
===     def __init__(self):
===         self._bar = 0
=== 
===     @property
===     def bar(self):
===         return self._bar
=== 
===     @bar.setter
===     def bar(self, value):
===         self._bar = value
=== 
=== class FooBar(Foo):
===     @Foo.bar.setter
===     def bar(self, value):
===         Foo.bar.fset(self, value)
=== 
=== f = FooBar()
=== f.bar = 5
=== print(f.bar)
5
>>> 

Keyboard

j / / n
next pair
k / / p
previous pair
1 / / h
show query pane
2 / / l
show candidate pane
c
copy suggested comment
r
toggle reasoning
g i
go to index
?
show this help
esc
close overlays

press ? or esc to close

copied