子分类列表之前要考虑什么? [英] What to consider before subclassing list?

查看:65
本文介绍了子分类列表之前要考虑什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近正在处理一个编码问题,有人在看代码,说子类列表不好(我的问题与该类无关).他说您不应该这样做,并且它会带来很多不良影响.这是真的吗?

I was recently going over a coding problem I was having and someone looking at the code said that subclassing list was bad (my problem was unrelated to that class). He said that you shouldn't do it and that it came with a bunch of bad side effects. Is this true?

我要问的是,列表通常对于子类来说不好,如果这样,原因是什么.或者,在使用Python子类化列表之前,应该考虑什么?

I'm asking if list is generally bad to subclass and if so, what are the reasons. Alternately, what should I consider before subclassing list in Python?

推荐答案

子类化list没有任何好处.所有方法都不会使用您重写的任何方法,因此您可能会遇到意外情况错误.此外,使用self.append而不是self.foos.append或尤其是self[4]而不是self.foos[4]来访问数据经常会造成混乱.您可以制作完全像列表一样的东西,或者(更好)更像您真正想要的列表,而只是子类化object.

There are no benefits to subclassing list. None of the methods will use any methods you override, so you can have unexpected bugs. Further, it's very often confusing doing things like self.append instead of self.foos.append or especially self[4] rather than self.foos[4] to access your data. You can make something that works exactly like a list or (better) howevermuch like a list you really want while just subclassing object.

这篇关于子分类列表之前要考虑什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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