简体   繁体   English

我怎么能提到应该在 Python 中返回父类的任何子类?

[英]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表示xElement类的一个实例。

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.

相关问题 如何在python中合并此父级和子级类? - How can I conjoin this parent and child class in python? 如何使用networkx绘制图形网络并询问Python中父节点和子节点之间是否应该存在连接? - How can I draw graphs network using networkx and asking if there should be connection between a parent and child node in Python? 如何确保每个子类都获得其父类属性的最新副本(在Python中)? - How can I ensure that every child class gets a fresh copy of its parent's class attributes (in Python)? 如何在父 class 中创建子 class 的 object? - How can I create an object of a child class inside parent class? 如何在子 class 中使用父 class 的属性 - How can I use attributes from a parent class in a child class 我怎样才能简单地将参数传递给子类中的父构造函数? - How can I simply pass arguments to parent constructor in child class? 如何在同一个 class 中将子 function 与父 function 连接? - How can I connect child function with parent function in same class? 如何将子 class 投射到其父级? - How can I cast a child class to its parent? 如何在子类中创建“子函数”,该子类既具有父函数又具有子函数? - How can I create a “Child function” in a child class that is a function with both the parent's function AND the Child's function? 我如何将父子关系转换成字典? - python - How can I convert parent - child relationship into a dictionary?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM