简体   繁体   English

方法的类型提示是什么?

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

What is the right type hint for a method ? method的正确类型提示是什么? There is typing.Callable , but I'm looking for a method type hint, and typing.Callable[[Self, ...], ...] is not working.typing.Callable ,但我正在寻找方法类型提示,而typing.Callable[[Self, ...], ...]不起作用。

I've tried this but it doesn't work:我试过这个但它不起作用:

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 is a type and not a type alias . MethodType 是一种类型而不是类型别名 Which type should I use then?那我应该使用哪种类型? I'm using Python 3.11.我正在使用 Python 3.11。

types.MethodType would be the annotation to use for "specifically a method object", but most of the time, typing.Callable will be more useful. types.MethodType将是用于“特定方法对象”的注释,但大多数时候, typing.Callable会更有用。

Callable applies to anything that is callable (functions, methods, classes, ...). 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

As an extension of this, if you want to type methods generically ie for the methods of subclasses of a base class, you can use a TypeVar :作为对此的扩展,如果您想要一般地键入方法,即对于基类 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