Python, subclassing immutable types
我有以下课程:
1 2 3 4 5 6 | class MySet(set): def __init__(self, arg=None): if isinstance(arg, basestring): arg = arg.split() set.__init__(self, arg) |
这按预期工作(用字符串中的单词而不是字母初始化集合)。但是,当我想对不可变版本的set执行同样的操作时,
1 2 3 4 5 6 | class MySet(frozenset): def __init__(self, arg=None): if isinstance(arg, basestring): arg = arg.split() frozenset.__init__(self, arg) |
我能用
是的,您需要覆盖
1 2 3 4 5 6 7 8 | class MySet(frozenset): def __new__(cls, *args): if args and isinstance (args[0], basestring): args = (args[0].split (),) + args[1:] return super (MySet, cls).__new__(cls, *args) print MySet ('foo bar baz') |
输出为:
1 | MySet(['baz', 'foo', 'bar']) |