【问题标题】:Extending FrozenSet from typing从打字中扩展 FrozenSet
【发布时间】:2020-09-18 00:45:22
【问题描述】:

我可能在这里做一些愚蠢的事情。对于那些想要复制和粘贴的人,请确保:

from typing import *

我使用的是 Python 3.7.4。

这个:

class S(FrozenSet[str]):
    def __init__(self, strs: Iterable[str], name: str):
            super().__init__(strs)
            self.name = name

S(['a'], 'a')

引发错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: S expected at most 1 arguments, got 2

,但是这个:

class S(Set[str]):
    def __init__(self, strs: Iterable[str], name: str):
            super().__init__(strs)
            self.name = name

S(['a'], 'a')

输出就好了:

S({'a'})

我想要一个集合的额外功能,但我不希望我的用户更改它。

编辑:我知道我可以只使用组合而不是继承,但如果我也能做到这一点,那就太好了。

【问题讨论】:

    标签: python constructor set frozenset


    【解决方案1】:

    因为它是一个frozenset,一旦创建,你就不能修改它的内容。

    因此,我认为你应该覆盖__new__

    class S(FrozenSet[str]):
        def __new__(cls, strs: Iterable[str], name: str):
            return super(S, cls).__new__(cls, strs)
    
        def __init__(self, strs: Iterable[str], name: str):
            self.name = name
    

    【讨论】:

    • 非常感谢!这行得通。我忘了创造不同于建造。
    猜你喜欢
    • 1970-01-01
    • 2019-09-18
    • 2020-11-18
    • 2021-08-10
    • 2019-01-06
    • 1970-01-01
    • 2019-05-04
    • 2019-03-22
    相关资源
    最近更新 更多