How to call a property of the base class if this property is being overwritten in the derived class?

前端 未结 7 754
無奈伤痛
無奈伤痛 2020-11-27 14:13

I\'m changing some classes of mine from an extensive use of getters and setters to a more pythonic use of properties.

But now I\'m stuck because some of my previous

7条回答
  •  孤街浪徒
    2020-11-27 15:01

    Some small improvements to Maxime's answer:

    • Using __class__ to avoid writing B. Note that self.__class__ is the runtime type of self, but __class__ without self is the name of the enclosing class definition. super() is a shorthand for super(__class__, self).
    • Using __set__ instead of fset. The latter is specific to propertys, but the former applies to all property-like objects (descriptors).
    class B(A):
        @property
        def prop(self):
            value = super().prop
            # do something with / modify value here
            return value
    
        @prop.setter
        def prop(self, value):
            # do something with / modify value here
            super(__class__, self.__class__).prop.__set__(self, value)
    

提交回复
热议问题