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

后端 未结 5 1821
梦谈多话
梦谈多话 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:53

    One approach I saw in this question is type hinting the self attribute. Together with Union from the typing package, you are able to use the attributes from a class which is used together with your mixin, while still having correct type hinting for own attributes:

    from typing import Union
    
    class AdditionMixin:
    
        def add(self: Union[MyBaseClass, 'AdditionMixin'], b: int) -> int:
            return self.value + b
    
    
    class MyBaseClass:
    
        def __init__(self, value: int):
            self.value = value
    

    Downside is that you have to add the hint to every method, which is kind of cumbersome.

提交回复
热议问题