pythonclassoverloadingsuper

Why is a parent class method calling the overloaded child method


I have a general parent class

  class Sensor():
    def writeCarac(self,uuid,PAYLOAD=None):
       pass
    def OTAReset(self):
       self.writeCarac(0x1234,[1,2,3,4])
 

and a child class

class sensortypeA(Sensor):
    def writeCarac(self, uuid):
        PAYLOAD = []
        match uuid:
            case uuid1:
                PAYLOAD = [something]
            case uuid2:
                PAYLOAD = [something else]
        return super().writeCarac(uuid, PAYLOAD)

writeCarac is overloaded in the child with a different prototype parameter list

If I have an instance of sensortypeA and I call writeCarac it works and I reach the child method. If I call OTAReset it calls the child method even though OTAReset is in the parent class.

I could try in OTAreset calling super but it makes no sense as it's already in the parent class.

I want to be able to call writeCarac inside the parent class but call the parent writeCarac method not the child one.


Solution

  • You could make sure to always call the method on the parent class:

    class Sensor():
        def writeCarac(self,uuid,PAYLOAD=None):
            pass
    
        def OTAReset(self):
            Sensor.writeCarac(self, 0x1234, [1,2,3,4])
    

    However, the signature for writeCarac should be identical on the parent and child classes. If you fix that then you can check if a non-default payload value has been passed and, only in that case, use the new defaults:

    class SensorTypeA(Sensor):
        def writeCarac(self, uuid, payload=None):
            if payload is None:
                payload = []
                match uuid:
                    case uuid1:
                        payload = [something]
                    case uuid2:
                        PAYLOAD = [something else]
    
            return super().writeCarac(uuid, payload)
    

    Once you do that then your original OTAReset code should work.