Python 父 class 函数的类型提示 returns 与调用 class 的类型相同?
Python Type Hint for parent class function that returns same type as calling class?
有没有一种方法可以键入提示父 class 函数以表明它 returns 与实际调用 class 的类型相同?
考虑一下:
- class B 继承自 class A 并实现了一个功能 func_b
- class A 有一个函数 func_a 即 returns 无论传入什么类型
- class B 的一个实例,“b”,调用 func_a 如下: b2 = b.func_a()
- 有没有办法输入提示 func_a(或其他东西),以便 IDE 将 b2.func_b() 视为有效调用?
'''
import __future__
class A:
def func_a(self) -> "A":
return self
class B(A):
def func_b(self) -> None:
print("func_b was called")
a = A()
a.func_a()
b = B()
b2 = b.func_a()
b2.func_a()
# IDE doesn't recognize that b2 is of class B and so b2.func_b() is white not yellow
# but still works
b2.func_b()
'''
func_b() 是白色而不是黄色:
您可以使用 Self
来自 typing
:
from typing import Self
class A:
def func_a(self) -> Self:
return self
您可以在此处找到更多详细信息:https://www.python.org/dev/peps/pep-0673/
有没有一种方法可以键入提示父 class 函数以表明它 returns 与实际调用 class 的类型相同?
考虑一下:
- class B 继承自 class A 并实现了一个功能 func_b
- class A 有一个函数 func_a 即 returns 无论传入什么类型
- class B 的一个实例,“b”,调用 func_a 如下: b2 = b.func_a()
- 有没有办法输入提示 func_a(或其他东西),以便 IDE 将 b2.func_b() 视为有效调用?
'''
import __future__
class A:
def func_a(self) -> "A":
return self
class B(A):
def func_b(self) -> None:
print("func_b was called")
a = A()
a.func_a()
b = B()
b2 = b.func_a()
b2.func_a()
# IDE doesn't recognize that b2 is of class B and so b2.func_b() is white not yellow
# but still works
b2.func_b()
'''
func_b() 是白色而不是黄色:
您可以使用 Self
来自 typing
:
from typing import Self
class A:
def func_a(self) -> Self:
return self
您可以在此处找到更多详细信息:https://www.python.org/dev/peps/pep-0673/