Search code examples
python-3.xabstract-classabstract

Python: Child Class Does not Specify all Args of Parent Abstract Method?


This might be a naive question, but I was wondering about the purpose of (both positional and keyword) arguments in a python function. For example:

from abc import ABC

class NeuralInference(ABC): 
    def __init__(self) -> None: 
        pass 
    
    @abstractmethod
    def train(self, training_batch_size: int): 
        raise NotImplementedError


class RatioEstimator(NeuralInference): 
    def __init__(self) -> None: 
        super().__init__()
    
    def train(self, wandb_flag: bool = False) -> None: 
        print(f"wandb_flag: {wandb_flag}")

ratio_estimator = RatioEstimator().train()

Now, this code is running, but I would have expected a bug, since RatioEstimator, which inherits from NeuralInference, does not have the argument training_batch_size specified. Could sb please explain why this is okay for Python?


Solution

  • ABC only cares if the derived class overrides all abstractethods. From the documentation:

    Using this decorator requires that the class’s metaclass is ABCMeta or is derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods and properties are overridden...

    Your RatioEstimator class overrides the train method, so you have fulfilled the abstractmethod contract.