相关疑难解决方法(0)

当抽象方法的参数可以具有从特定基类型派生的任何类型时,如何注释该参数的类型?

当参数可以具有从特定基类型派生的任何类型时,如何注释抽象方法的函数参数的类型?

例子:

import abc
import attr

@attr.s(auto_attribs=True)
class BaseConfig(abc.ABC):
    option_base: str

@attr.s(auto_attribs=True)
class ConfigA(BaseConfig):
    option_a: str

@attr.s(auto_attribs=True)
class ConfigB(BaseConfig):
    option_b: bool


class Base(abc.ABC):
    @abc.abstractmethod
    def do_something(self, config: BaseConfig):
        pass

class ClassA(Base):
    def do_something(self, config: ConfigA):
        # test.py:27: error: Argument 1 of "do_something" is incompatible with supertype "Base"; supertype defines the argument type as "BaseConfig"
        print("option_a: " + config.option_a)

class ClassB(Base):
    def do_something(self, config: ConfigB):
        # test.py:33: error: Argument 1 of "do_something" is incompatible with supertype "Base"; supertype defines the argument …
Run Code Online (Sandbox Code Playgroud)

oop python-3.x mypy python-3.8 python-typing

7
推荐指数
1
解决办法
730
查看次数

标签 统计

mypy ×1

oop ×1

python-3.8 ×1

python-3.x ×1

python-typing ×1