开发者

Python, subclassing immutable types

I've the following class:

class MySet(set):

    def __init__(self, arg=None):
        if isin开发者_Python百科stance(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__ ?


Yes, you need to override __new__ special method:

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

And the output is:

MySet(['baz', 'foo', 'bar'])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜