类型提示:类型类的参数 [英] Type Hinting: Argument Of Type Class
问题描述
我正在定义一个方法
def foo_my_class(my_class: ???, bar: str) -> None:
""" Operate on my_class """
我想知道,如何使用类型提示功能来指定应在第一个参数中传递该类.
I wonder, how can I use type hinting feature to specify that class should be passed in the first argument.
基本上,我应该在那里放什么而不是 ???
标记?
Basically, what should I put instead of ???
mark up there?
这里还有一些代码,可以更具体地说明我要实现的目标.
Here is some more code to be more specific on what I am trying to achieve.
class Base(object):
"""base class"""
class X(Base):
"""some class"""
class Y(Base):
"""some other class"""
foo_my_class(X, "foo")
foo_my_class(Y, "bar")
推荐答案
您只需使用类本身.
def foo_my_class(my_class: MyClass, bar: str) -> None:
来自PEP(重点是我的):
类型提示可以是内置类(包括在标准库或第三方扩展模块中定义的类)、抽象基类、types
模块中可用的类型和用户-定义的类(包括在标准库或第三方模块中定义的类).
Type hints may be built-in classes (including those defined in standard library or third-party extension modules), abstract base classes, types available in the
types
module, and user-defined classes (including those defined in the standard library or third-party modules).
这篇关于类型提示:类型类的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!