如何在 Python 中输入类的对象也遵守协议的提示?

Far*_* ET 7 python type-hinting mypy

我有一组类,让我们称它们为Foo和,它们都继承自当前范围之外定义的Bar基类(不是由我定义的)。Father我定义了一个DummyProtocol具有 function 的协议类do_something

class DummyProtocol(Protocol):
   def do_something(self):
      ...
   

class Foo(Father):
   def do_something(self):
      pass

class Bar(Father):
   def do_something(self):
      pass

Run Code Online (Sandbox Code Playgroud)

我有一个功能create_instance

def create_dummy_and_father_instance(cls, *args, **kwargs):
    return cls(*args, **kwargs)
Run Code Online (Sandbox Code Playgroud)

我想以某种方式提示它,即 cls 被提示接受一个Father也实现DummyProtocol.

所以我将函数更改为 this 以表明 cls 是一个继承自 和 的Father类型DummyProtocol

def create_dummy_and_father_instance(
    cls: Type[tuple[Father, DummyProtocol]], *args, **kwargs
):
    return cls(*args, **kwargs)
Run Code Online (Sandbox Code Playgroud)

但我在以下位置收到此错误mypy

Cannot instantiate type "Type[Tuple[Father, DummyProtocol]]"
Run Code Online (Sandbox Code Playgroud)

hus*_*sic 2

您可以定义第二个Father类,它继承自Father和Protocol(另请参阅mypy:如何验证类型是否具有多个超类):

class DummyProtocol(Protocol):

    def do_something(self):
        ...
    
class Father:
    pass
    
class Father2(Father, DummyProtocol):
    pass
    
class Foo(Father2):

    def do_something(self):
        pass
    
class Bar(Father2):

    def do_something(self):
        pass
    
class FooNot(Father):
    pass
    
def create_dummy_and_father_instance(
    cls: Type[Father2]
):
    return cls()
    
create_dummy_and_father_instance(Foo)
create_dummy_and_father_instance(Bar)
create_dummy_and_father_instance(FooNot)  # mypy error ok
Run Code Online (Sandbox Code Playgroud)

  • 但这不是违反协议的使用吗?协议仅涉及静态类型提示,而不涉及运行时影响,不是吗? (3认同)