【发布时间】: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 很酷,很高兴知道。谢谢你提醒我!