在Python中,如何正确注释函数以显示与类成员函数相同的返回类型?

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

我使用 Python 3.11 和 mypy 作为类型检查器。这是我正在尝试做的一个例子。

from dataclasses import dataclass
from abc import ABC, abstractmethod
from typing import Any, TypeVar, Generic

class MyBase(ABC):
    @abstractmethod
    def my_func(self, *args, **kwargs) -> Any:
        raise NotImplementedError

class Bar(MyBase):
    def my_func(self, *args, **kwargs) -> int:
        return 5

class Baz(MyBase):
    def my_func(self, *args, **kwargs) -> str:
        return 'Hello'

T = TypeVar('T', bound=MyBase)

@dataclass
class Foo(Generic[T]):
    value: T

    def foo_call(self) -> ???:  # What do I put here? I want something like T.my_func.__annotations__['return']
        return self.value.my_func()

myFoo: Foo[Bar] = Foo(value=Bar())
myFoo.foo_call()  # this should give a return type-hint of int

我可以将 myFoo 声明为 Foo[int],并使用 foo_call(self) -> T,但是如果对 Bar.my_func 的返回类型进行任何更改,则无法正确更新。正确的方法是什么?

python generics type-hinting mypy python-3.11
1个回答
0
投票

最有可能的是,MyBase 应该是通用的,而 Foo 的参数应该是

my_func
返回类型,而不是
MyBase
子类:

from dataclasses import dataclass
from abc import ABC, abstractmethod
from typing import TypeVar, Generic

T = TypeVar('T')

class MyBase(ABC, Generic[T]):
    @abstractmethod
    def my_func(self, *args, **kwargs) -> T:
        raise NotImplementedError

class Bar(MyBase[int]):
    def my_func(self, *args, **kwargs) -> int:
        return 5

class Baz(MyBase[str]):
    def my_func(self, *args, **kwargs) -> str:
        return 'Hello'

@dataclass
class Foo(Generic[T]):
    value: MyBase[T]

    def foo_call(self) -> T:
        return self.value.my_func()
© www.soinside.com 2019 - 2024. All rights reserved.