Python:如何从内置列表类型继承? [英] Python: How can I inherit from the built-in list type?

查看:25
本文介绍了Python:如何从内置列表类型继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想给内置的list类型添加一些属性,所以我写了这个:

I want to add some attributes to the built-in list type, so I wrote this:

class MyList(list):
    def __new__(cls, *args, **kwargs):
        obj = super(MyList, cls).__new__(cls, *args, **kwargs)
        obj.append('FirstMen')
        return obj

    def __init__(self, *args, **kwargs):
        self.name = 'Westeros'

    def king(self):
        print 'IronThrone'

if __name__ == '__main__':
    my_list = MyList([1, 2, 3, 4])
    print my_list

但是my_list 只包含元素'FirstMen'.为什么我的 __new__ 在这里不起作用?我应该如何从像 list 这样的内置类型继承?像 str 这样的不可变类型是一样的吗?

but my_list contains only the element 'FirstMen'. Why my __new__ doesn't work here? And how should I inherit from a built-in type like list? Is it the same for the immutable types like str?

推荐答案

list 类型通常在它的 __init__() 方法中执行列表的实际初始化,如它是可变类型的约定.你只需要在对不可变类型进行子类型化时覆盖 __new__() .虽然您在子类化列表时可以覆盖 __new__() ,但对于您的用例来说这样做没有多大意义.覆盖 __init__() 更容易:

The list type usually does the actual initialisation of the list inside its __init__() method, as it is the convention for mutable types. You only need to overwrite __new__() when subtyping immutable types. While you can overwrite __new__() when subclassing list, there is not much point in doing so for your use case. It's easier to just overwrite __init__():

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'

另请注意,我建议不要在这种情况下使用 super().你想在这里调用 list.__init__() ,而不是其他任何东西.

Also note that I recommend against using super() in this case. You want to call list.__init__() here, and not possibly anything else.

这篇关于Python:如何从内置列表类型继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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