【问题标题】:Define custom type hint with lists in Python 3.6在 Python 3.6 中使用列表定义自定义类型提示
【发布时间】:2021-09-08 10:01:38
【问题描述】:

我正在尝试定义一个新的类型提示,但是,它不允许我在 Python 3.6 中执行此操作,我想知道是否有任何解决方法。这是我的示例代码,我想要我自己的类,它将列表作为字段:

class T(type):

    def __new__(cls, nums):
        return super().__new__(cls, f'T((nums))', (T,),{})

    def __init__(self, nums):
        self.__origin__ = T
        self.__args__ = nums

每当我尝试实际使用它时,我都会得到

'type' object is not subscriptable

如果我定义了一个不涉及列表的自定义类型提示,则代码有效。无论如何我可以在 python3.6 中定义自定义类型提示吗?

【问题讨论】:

    标签: python-3.x types python-3.6 type-hinting


    【解决方案1】:

    您需要了解类型提示是针对对象(或数据类型)的。您不能创建继承自 type 的自定义类。如果您想创建一个新的数据类型,那么只需从object 继承即可。虽然,即使从对象继承也不是必需的,因为在 python 中一切都是对象,但它通常被认为是一种好习惯。

    class T(object):
      def __init__(self, val):
        self.__val = val
    
      def __str__(self):
        return self.__val
    
    t = T(10)
    print(t) # 10
    print(type(t)) # <class '__main__.T'>
    

    【讨论】:

      猜你喜欢
      • 2022-08-18
      • 1970-01-01
      • 2016-02-23
      • 2020-11-23
      • 1970-01-01
      • 2019-05-18
      • 2019-05-19
      • 2017-06-18
      相关资源
      最近更新 更多