python - `[]`模块类中的 `typing`是如何实现的?

标签 python

使用typing模块你可以写

from typing import Dict
my_type: Dict[str, int]

Dict 是一个类。我的问题是:类名后面的括号是什么。 python 的哪个语法方面允许该语法?我怎样才能在自己的类(class)中做类似的事情?

最佳答案

感谢 @timgeb 为我指明了正确的方向。事实证明它确实使用了 __getitem__。但是,由于 __getitem__ 引用一个实例,您必须在当前类是其实例的对象中定义它。所以,你必须使用元类。例如

class Root(type):
    def __getitem__(self, i):
        print(f'arguments: {i}')


class MyDict(metaclass=Root):
    pass

现在,用

MyDict[list, str]

你得到

arguments: (<class 'list'>, <class 'str'>)

关于python - `[]`模块类中的 `typing`是如何实现的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52851753/

相关文章:

python - AWS Lambda 函数中的音频文件到文本转换

python - tensorflow 语法网 : Where are sentence_pb2 and gen_parser_ops?

python - pandas.DataFrame.shift() fill_value 不工作

python - CUDA 不支持边界检查

python - cv2.HoughCircles 的结果不可靠

python - 从 numpy 数组 python 中提取索引

python - Python 在更大的团队中工作吗?

python - pip 安装不起作用,InvalidSchema : Missing dependencies for SOCKS support

python - 如何根据条件有效地重新排序行?

python - 安装 python 模块自定义位置 PYTHONUSERBASE/virtualenv