[英]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.