繁体   English   中英

从打字中扩展 FrozenSet

[英]Extending FrozenSet from typing

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

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'})

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

编辑:我知道我可以在 inheritance 上使用合成,但如果我也能做到这一点会很好。

因为它是一个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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM