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

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

问题描述

我想在内置的列表类型中添加一些属性,所以我写了这个:

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天全站免登陆