Python,子类化不可变类型 [英] Python, subclassing immutable types

查看:118
本文介绍了Python,子类化不可变类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

class MySet(set):

    def __init__(self, arg=None):
        if isinstance(arg, basestring):
            arg = arg.split()
        set.__init__(self, arg)

这可以按预期工作(使用字符串的单词而不是字母来初始化集合).但是,当我想对set的不可变版本执行相同操作时,__init__方法似乎被忽略了:

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)

我可以用__new__达到类似的目的吗?

Can I achieve something similar with __new__ ?

推荐答案

是的,您需要覆盖__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')

输出为:

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

这篇关于Python,子类化不可变类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆