我可能是在做傻事。对于想要复制和粘贴的人,请确保:
from typing import *我正在使用Python3.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'})我想要一个集的额外功能,但我不希望我的用户改变它。
编辑:我知道我可以使用组合而不是继承,但是如果我也能让它工作的话,那就太好了。
发布于 2020-05-30 14:00:23
因为它是一个冻结集,一旦创建,您就不能修改它的内容。
因此,我认为您应该重写__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 = namehttps://stackoverflow.com/questions/62103042
复制相似问题