【问题标题】:Using class variable for type hinting in __init__在 __init__ 中使用类变量进行类型提示
【发布时间】:2022-01-17 19:49:39
【问题描述】:

在 Python 中,我的类中有一个“允许的类型”列表,在构造函数中,我想传递一个必须在该允许类型列表中的参数。所以,从概念上讲,这就是我想要的:

from typing import Union

class A:
  allowed_types = [typeA, typeB]

  def __init__(self, some_argument: Union[allowed_types]):
     (do stuff)

我不确定如何解决这个问题。你会如何设置这样的东西?也许对此有更好的设置,但我不确定如何。谢谢!

【问题讨论】:

    标签: python type-hinting python-typing


    【解决方案1】:

    我会在你的构造函数中使用它:

    for element in some_argument:
        # This will throw an error if the type is not in the approved types.
        assert type(element) in approved_types
    

    【讨论】:

      【解决方案2】:

      首先,如果您使用的是 Python3.9+,建议使用本机类型而不是打字类型。 (例如:list > typing.List, set > typing.Set)

      其次,在 Python 3.10+ 上,您可以执行 Type1 |用于工会的 Type2 要好得多。所以对于类型提示: def func(var: Type1 | Type2)

      第三,如果您可以接受多种类型,请花点时间考虑一下您的应用程序。这些类型有关系吗?也许他们应该被继承?例如,如果您有 allowed_types = [TaxCalc, AmortCalc],那么您的类型可能应该有一个共同的父 BaseCalc 或 CalcInterface,您可以将其作为类型提示传递。否则检查我上面是怎么做的

      要实际回答,我会亲自回答;你只需将联合创建为一种类型,然后传递它。但不知道为什么你想在课堂上使用它。通常我将自定义类型定义放在一个文件中并从那里导入。

      例如,我在大多数项目中都有一个名为“type_extensions.py”的文件,它看起来像这样:

      Number_t = int | float | complex
      String_t = str | bytes
      

      这是一个:https://github.com/zkscpqm/python-common/blob/master/types_extensions.py

      【讨论】:

        【解决方案3】:

        如果您只想确保 some_argument 是特定类型列表的实例,您可以执行以下操作:

        class A:
            allowed_types = [int,float]
        
            def __init__(self,some_argument):
                if type(some_argument) in self.allowed_types:
                    self.some_argument = some_argument
                else:
                    raise TypeError("some_argument must be of type {}".format(self.allowed_types))
        
        # raise a TypeError if some_argument is not of type int or float
        A("1")
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-09-28
          • 1970-01-01
          • 2011-02-11
          • 2017-08-14
          • 2019-06-04
          • 2019-02-20
          • 2022-01-24
          • 2010-12-21
          相关资源
          最近更新 更多