Python - extending properties like you'd extend a function

前端 未结 4 1584
甜味超标
甜味超标 2021-01-11 17:42

Question

How can you extend a python property?

A subclass can extend a super class\'s function by calling it in the overloaded version, a

4条回答
  •  时光说笑
    2021-01-11 18:19

    You should be calling the superclass properties, not bypassing them via self._dataframe. Here's a generic example:

    class A(object):
    
        def __init__(self):
            self.__prop = None
    
        @property
        def prop(self):
            return self.__prop
    
        @prop.setter
        def prop(self, value):
            self.__prop = value
    
    class B(A):
    
        def __init__(self):
            super(B, self).__init__()
    
        @property
        def prop(self):
            value = A.prop.fget(self)
            value['extra'] = 'stuff'
            return value
    
        @prop.setter
        def prop(self, value):
            A.prop.fset(self, value)
    

    And using it:

    b = B()
    b.prop = dict((('a', 1), ('b', 2)))
    print(b.prop)
    

    Outputs:

    {'a': 1, 'b': 2, 'extra': 'stuff'}
    

    I would generally recommend placing side-effects in setters instead of getters, like this:

    class A(object):
    
        def __init__(self):
            self.__prop = None
    
        @property
        def prop(self):
            return self.__prop
    
        @prop.setter
        def prop(self, value):
            self.__prop = value
    
    class B(A):
    
        def __init__(self):
            super(B, self).__init__()
    
        @property
        def prop(self):
            return A.prop.fget(self)
    
        @prop.setter
        def prop(self, value):
            value['extra'] = 'stuff'
            A.prop.fset(self, value)
    

    Having costly operations within a getter is also generally to be avoided (such as your parse method).

提交回复
热议问题