【问题标题】:Python: Subclassing frozenset not iterable?Python:子类化frozenset不可迭代?
【发布时间】:2014-06-07 17:57:21
【问题描述】:

子类化 frozenset 和 set 在 iterables 方面似乎不一样。尝试运行以下 MWE:

class MonFrozenSet(frozenset):
    def __new__(self, data):
        super(MonFrozenSet,self).__init__(data)
        return self

class MonSet(set):
    def __init__(self, data):
        super(MonSet,self).__init__(data)



x=(1,2,3,4)

A=MonSet(x)
B=MonFrozenSet(x)

for y in A: #Works
    print y

for y in B: #Doesn't work
    print y

第二个for 返回:

for y in B:
TypeError: 'type' object is not iterable

知道如何解决这个问题吗?

如果您问自己为什么要使用frozenset,答案是我正在尝试创建一组元组。元组的集合将是frozenset,元组的集合将是一个集合。

我使用 Python-2.7

【问题讨论】:

    标签: python python-2.7 types set subclassing


    【解决方案1】:

    当覆盖__new__ 时,您需要调用超类的__new__,而不是它的__init__。此外,您需要传递self(最好命名为cls),因为__new__ 是一个类方法。另外,您需要返回结果,因为__new__ 实际上创建了一个对象,它不会修改self。所以:

    class MonFrozenSet(frozenset):
        def __new__(cls, data):
            return super(MonFrozenSet,cls).__new__(cls, data)
    

    然后:

    >>> a = MonFrozenSet([1, 2, 3])
    >>> for item in a:
    ...     print item
    1
    2
    3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-31
      • 1970-01-01
      • 2020-09-12
      • 2011-03-08
      • 2022-11-03
      • 1970-01-01
      相关资源
      最近更新 更多