【问题标题】:How to allow only elements of a specific class to be elements of an iterable (for a custom class)如何只允许特定类的元素成为可迭代的元素(对于自定义类)
【发布时间】:2017-07-23 16:03:14
【问题描述】:

就我而言,我想定义一个自定义类(称为 WordTuple),它是元组类的子类。此自定义元组的元素必须全部属于另一个自定义类(称为 Word)。

我知道这个问题(How to make an iterable class in Python in which only a specific type is allowed to be the element?)很相似,但答案不是我要找的,也不是我很清楚。

class Word(str):
    pass

class WordTuple(tuple):
    # Here whatever is necessary for the elements of this particular tuple
    # to be all members of the class 'Word'
    pass

【问题讨论】:

  • 你不能在 init 中强制执行它吗?每次初始化此类时,您都可以使用 isinstance 验证数据类型
  • @orizis 标准的内置不可变类型在__new__ 方法中初始化,而不是在__init__ 中。有更多关于此的信息here
  • @PM2Ring 很酷,很高兴知道。谢谢你提醒我!

标签: python class oop tuples


【解决方案1】:

因为元组是不可变的,所以您只需要在创建元组时验证对象。您可以在自定义__new__ method 中这样做:

class WordTuple(tuple):
    def __new__(cls, *objs):
        if not all(isinstance(o, Word) for o in objs):
            raise TypeError('WordTuple can only contain Word instances')
        return super().__new__(cls, objs)

演示:

>>> WordTuple('a', 'b')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in __new__
TypeError: WordTuple can only contain Word instances
>>> WordTuple(Word('a'), Word('b'))
('a', 'b')

【讨论】:

    猜你喜欢
    • 2018-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 2019-04-07
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多