Python - extending properties like you'd extend a function

前端 未结 4 1625
甜味超标
甜味超标 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:34

    If I understand correctly what you want to do is call the parent's method from the child instance. The usual way to do that is by using the super built-in.

    I've taken your tongue-in-cheek example and modified it to use super in order to show you:

    class NormalMath(object):
        def __init__(self, number):
            self.number = number
    
        def add_pi(self):
            n = self.number
            return n + 3.1415
    
    
    class NewMath(NormalMath):
        def add_pi(self):
            # this will call NormalMath's add_pi with
            normal_maths_pi_plus_num = super(NewMath, self).add_pi()
            return int(normal_maths_pi_plus_num)
    

    In your Log example, instead of calling:

    self._dataframe = LogFile.dataframe.getter() 
    

    you should call:

    self._dataframe = super(SensorLog, self).dataframe
    

    You can read more about super here

    Edit: Even thought the example I gave you deals with methods, to do the same with @properties shouldn't be a problem.

提交回复
热议问题