Python,子类化不可变类型
我有以下课程:
class MySet(set):
def __init__(self, arg=None):
if isinstance(arg, basestring):
arg = arg.split()
set.__init__(self, arg)
这按预期工作(使用字符串的单词而不是字母初始化集合)。但是,当我想对 set 的不可变版本执行相同操作时, __init__
方法似乎被忽略:
class MySet(frozenset):
def __init__(self, arg=None):
if isinstance(arg, basestring):
arg = arg.split()
frozenset.__init__(self, arg)
我可以使用 __new__
实现类似的功能吗?
I've the following class:
class MySet(set):
def __init__(self, arg=None):
if isinstance(arg, basestring):
arg = arg.split()
set.__init__(self, arg)
This works as expected (initialising the set with the words of the string rather than the letters). However when I want to do the same with the immutable version of set, the __init__
method seems to be ignored:
class MySet(frozenset):
def __init__(self, arg=None):
if isinstance(arg, basestring):
arg = arg.split()
frozenset.__init__(self, arg)
Can I achieve something similar with __new__
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,您需要重写 __new__ 特殊方法:
输出为:
Yes, you need to override
__new__
special method:And the output is: