繁体   English   中英

方法的类型提示是什么?

[英]What is the type hint for a method?

method的正确类型提示是什么? typing.Callable ,但我正在寻找方法类型提示,而typing.Callable[[Self, ...], ...]不起作用。

我试过这个但它不起作用:

class _Object:
    """An empty object for method type."""

    def method(self) -> None:
        """
        A method.

        :return None: Nothing.
        """
        return None


MethodType: Type = type(_Object().method)

MethodType 是一种类型而不是类型别名 那我应该使用哪种类型? 我正在使用 Python 3.11。

types.MethodType将是用于“特定方法对象”的注释,但大多数时候, typing.Callable会更有用。

Callable适用于任何callable的东西(函数、方法、类……)。

from typing import Callable, TypeAlias  # TypeAlias available thru typing-extensions for Python <= 3.9


class MyBase:

    def method(self, i: int, j: int) -> int:
        return i + j


MethodType: TypeAlias = Callable[[MyBase, int, int], int]
a: MethodType = MyBase.method  # if you want to use a TypeAlias

b: Callable[[MyBase, int, int], int] = MyBase.method  # self must provided explicitly

my_base = MyBase()
c: Callable[[int, int], int] = my_base.method  # self is provided implicitly

作为对此的扩展,如果您想要一般地键入方法,即对于基类 class 的子类的方法,您可以使用TypeVar

from typing import TypeVar

T = TypeVar("T", bound=MyBase)  # T is either an instance of MyBase or a subclass of MyBase


class MyDerived(MyBase):
    ...


def my_decorator(my_function: Callable[[MyBase, int, int], int]) -> Callable[[MyBase, int, int], int]:
    return my_function


def my_generic_decorator(my_function: Callable[[T, int, int], int]) -> Callable[[T, int, int], int]:
    return my_function


my_decorator(MyDerived.method)  # Parameter 1: type "MyBase" cannot be assigned to type "MyDerived"
my_generic_decorator(MyDerived.method)  # OK

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM