(任何)类的 Python 类型提示 [英] Python type hint for (any) class

查看:47
本文介绍了(任何)类的 Python 类型提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想输入提示以下函数:

I want to type hint the following function:

def get_obj_class(self) -> *class*:
  return self.o.__class__

self.o 可以是任何类型,在运行时确定.

self.o could be of any type, it's determined at runtime.

*class* 显然不是这里的答案,因为它是无效的语法.但是正确答案是什么?我找不到任何关于此的文档,感谢您的帮助.

*class* obviously is not the answer here, because it's invalid syntax. But what is the right answer? I could not find any documentation on this, any help is appreciated.

同样,如果我有一个返回 cls 实例的函数 f(cls: *class*),有没有办法输入提示适当地返回值?

On a similar note, if I have a function f(cls: *class*) which returns an instance of cls, is there a way to type hint the return value appropriately?

推荐答案

我建议结合使用 TypeVar,表示您的 self.o 值可以是任意类型,Type,方法如下:

I'd recommend using a combination of TypeVar, to indicate that your self.o value could be any arbitrary type, and Type, in the following way:

from typing import TypeVar, Type

T = TypeVar('T')

class MyObj:
    def __init__(self, o: T) -> None:
        self.o = o

    def get_obj_class(self) -> Type[T]:
        return type(self.o)

def accept_int_class(x: Type[int]) -> None:
    pass

i = MyObj(3)
foo = i.get_obj_class()
accept_int_class(foo)    # Passes

s = MyObj("foo")
bar = s.get_obj_class()
accept_int_class(bar)    # Fails

如果你想让 o 的类型更加动态,你可以显式或隐式地给它一个 Any 类型.

If you want the type of o to be even more dynamic, you could explicitly or implicitly give it a type of Any.

关于你的后一个问题,你会这样做:

Regarding your latter question, you'd do:

def f(cls: Type[T]) -> T:
    return cls()

请注意,在实例化类时需要小心——我不记得 Pycharm 在这里做了什么,但我知道 mypy 目前不会检查以确保您正在调用 __init__ 正确运行/使用正确数量的参数.

Note that you need to be careful when instantiating your class -- I don't remember what Pycharm does here, but I do know that mypy currently does not check to make sure you're calling your __init__ function correctly/with the right number of params.

(这是因为 T 可以是任何东西,但无法暗示构造函数应该是什么样子,因此执行此检查最终要么不可能,要么非常困难.)

(This is because T could be anything, but there's no way to hint what the constructor ought to look like, so performing this check would end up being either impossibly or highly difficult.)

这篇关于(任何)类的 Python 类型提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆