Search code examples
pythonclassoopinheritancemethods

Pass the child class name as an argument of inherited class method


how are you doing?

I'm not facing a problem exactly, but I want to improve the code and I don't know how. The 'problem' is:

I have a parent class:

class Utils:

    @staticmethod
    def jsonFromDict(className, dict):
        # code logic here 
        return className(**finalValue)

and then I have a bunch of dataclasses, like:

@dataclass
class payloadA(Utils):

   x: str = ''
   y: str = ''
   z: str = ''

I want to pass the class name to the jsonFromDict without the need to repeat the class name. Today I'm doing in this way:

payloadA.jsonFromDict(payloadA, dict)
payloadB.jsonFromDict(payloadB, dict)
payloadC.jsonFromDict(payloadC, dict)

I don't want to override or to repeat the implementation inside each payload class, but I can't find a way to pass the class name, from the instance which I'm calling the parent's method, to the parent's method.

Is there any way I can do this?

I've tried to override inside each class but I want to keep it DRY


Solution

  • You want an alternative constructor, which and the idiomatic way to do that in Python is with a classmethod. Your base class is acting as a mixin, so I renamed it.

    class ConstructorMixin:
        @classmethod
        def jsonFromDict(cls, dict):
            # code logic here 
            return cls(**finalValue)
    
    
    @dataclass
    class PayloadA(ConstructorMixin):
    
       x: str = ''
       y: str = ''
       z: str = ''
    
    
    pl = PayloadA.jsonFromDict(some_dict)