如何向静态类型检查器指示库基类的特定方法必须在我们的子类中重新实现?

问题描述 投票:0回答:1

我使用协议来强制我们的子类应该实现额外的方法并定义额外的属性。但我还想强制要求基类的特定方法必须在我们的子类中重新实现。这可能吗?

### From some lib: ###

class BaseFoo:
    def a_really_nice_func(intparam: int) -> str:
        print("This is the base behaviour")

### End lib ### 

### Start my code: ###

class OurBaseFooProtocol(Protocol):
    description: str
    
    def a_really_nice_func(intparam: int) -> str:
       ...
    

# We need to implement a lot of classes like this:
class Foo(BaseFoo, OurBaseFooProtocol):
    description = "I like trains" # Correctly gives an error if it's not defined
    
    # but if I don't define `a_really_nice_func`, it doesn't complain - because it's defined in `BaseFoo`.
    # How do I force all subclasses of BaseFoo that implement the OurBaseFoo protocol 
    # to *re-implement `a_really_nice_func`? 

编辑 - 注意:

我最初将其实现为 ABC:


class OurBaseFoo(BaseFoo, ABC):
    description: str
    
    @abstractmethod
    def a_really_nice_func(intparam: int) -> str:
        raise NotImplementedError

但是,不幸的是,当我们的子类没有定义

description
属性时,这不允许 mypy/pyright 显示错误。

python mypy python-typing pyright
1个回答
0
投票

不确定 mypy 或 Pyright,但我希望这有帮助

class A:
    description: str
    def __new__(cls, *args, **kwargs):
        instance = super().__new__(cls)
        if instance.description==None:
            raise ValueError("description is None")
        return instance
        
class B(A):
    pass
    
class C(A):
    description: str = "class C"
    
try:
    newclass = B()
except Exception:
    newclass = C()
    
print(type(newclass))

与@abstractmethod结合使用

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.