How do I correctly add type-hints to Mixin classes?

后端 未结 5 1822
梦谈多话
梦谈多话 2021-02-13 02:33

Consider the following example. The example is contrived but illustrates the point in a runnable example:

class MultiplicatorMixin:

    def multiply(self, m: in         


        
5条回答
  •  星月不相逢
    2021-02-13 02:48

    For reference, mypy recommends to implement mixins through a protocol (https://mypy.readthedocs.io/en/latest/more_types.html#advanced-uses-of-self-types).

    It works with mypy >= 750.

    from typing_extensions import Protocol
    
    
    class HasValueProtocol(Protocol):
        @property
        def value(self) -> int: ...
    
    
    class MultiplicationMixin:
    
        def multiply(self: HasValueProtocol, m: int) -> int:
            return self.value * m
    
    
    class AdditionMixin:
    
        def add(self: HasValueProtocol, b: int) -> int:
            return self.value + b
    
    
    class MyClass(MultiplicationMixin, AdditionMixin):
    
        def __init__(self, value: int) -> None:
            self.value = value
    

提交回复
热议问题