[英]How can I mention there should return any child of parent class in Python?
class Element:
def __call__(self, *args, **kwargs):
print('Hello')
return self
class Button(Element):
pass
class TextBox(Element):
pass
def some_func(element: Element) -> Element:
return element()
some_func(Button)
some_func(TextBox)
Pycharm mentions "Expected type 'Element', got 'Type[Button]' instead ". Pycharm 提到“预期类型 'Element',得到了 'Type[Button]' ”。 Is there any proper way to get type of the return as parent of all it's children?
是否有任何适当的方法可以将返回类型作为所有孩子的父母?
I use Type[Element].我使用类型 [元素]。 It seems works fine.
它似乎工作正常。 But my friend told me that it means an instance of the class but not the class itself.
但我的朋友告诉我,这意味着类的一个实例,而不是类本身。 Seems like right answer is
some_func(element: t.Type[_T]) -> _T
, where _T = t.TypeVar('_T', bound='Element')
and import typing as t
was performed.似乎正确的答案是
some_func(element: t.Type[_T]) -> _T
,其中_T = t.TypeVar('_T', bound='Element')
并import typing as t
。 But it's not very readable, so I prefer use Type[Element].但它的可读性不是很好,所以我更喜欢使用 Type[Element]。 Thank you all!
谢谢你们! And especialy thanks to SUTerliakov.
特别感谢 SUTerliakov。
x: Element
means that x
is an instance of the Element
class. x: Element
表示x
是Element
类的一个实例。
Use type[Element]
when you mean to pass a subclass of Element
.当您要传递 Element 的子类时,请使用
type[Element]
Element
def some_func(element: type[Element]) -> Element:
return element()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.