简体   繁体   中英

python typing abstractmethod with default arguments

I'm a little confuse how I'm supposed to type a base class abstract method?

In this case my base class only requires that the inheriting class implements a method named 'learn' that returns None without mandating any arguments.

class MyBaseClass(ABC):
    @abstractmethod
    def learn(self, *args, **kwargs) -> None:
       raise NotImplementedError()

but if I implement it mypy raise en error 'Signature of "learn" incompatible with supertype "MyBaseClass"'

class MyOtherClass(MyBaseClass):
    def learn(self, alpha=0.0, beta=1) -> None:
       # do something
       return None

So how should I declare the learn method in the base class?

First things first, I'd ask why you want a method without known arguments. That sounds like a design problem.

One solution

It's fine to add new parameters to subclasses if those parameters have default values (and the base class doesn't use **kwargs ), like

class MyBaseClass:
    @abstractmethod
    def learn(self) -> None:
       raise NotImplementedError()

class MyOtherClass(MyBaseClass):
    def learn(self, alpha=0.0, beta=1) -> None:
       ...

though you won't be able to specify alpha and beta if you only know it's a MyBaseClass :

def foo(x: MyOtherClass) -> None:
    x.learn(alpha=3)  # ok

def foo(x: MyBaseClass) -> None:
    x.learn(alpha=3)  # not ok

Why didn't *args, **kwargs work?

If you have

class MyBaseClass(ABC):
    @abstractmethod
    def learn(self, *args, **kwargs) -> None:
       raise NotImplementedError()

then consider the function

def foo(x: MyBaseClass) -> None:
    ...

In that function, you can pass anything to x.learn , for example x.learn(1, fish='three') . This has to be true for any x . Since x can be an instance of a subclass of MyBaseClass (such as MyOtherClass ), that subclass must also be able to accept those arguments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM