Python,子类化不可变类型

发布于 2024-09-07 14:14:03 字数 526 浏览 6 评论 0原文

我有以下课程:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蓝礼 2024-09-14 14:14:03

是的,您需要重写 __new__ 特殊方法:

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

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'])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文