简体   繁体   English

为什么 python 字符串不是列表的子类?

[英]Why isn't a python string a subclass of list?

This honestly just feels super weird to me.老实说,这对我来说感觉非常奇怪。 I've been learning python for only a couple of days, but I can't help but feel weirded out at the fact that list and string are treated differently in some cases, most notably in the fact that strings are immutable.我学习 python 才几天时间,但我不禁感到奇怪,因为在某些情况下列表和字符串的处理方式不同,尤其是字符串是不可变的。 Was it made like this because there isn't a real character object in python, so strings couldn't have been treated as a list of characters?是不是因为python中没有真正的字符object,所以字符串不能被当作字符列表来处理? I am probably talking gibberish, but I still hope someone much more knowledgeable could perhaps give me some further insight into this.我可能在胡言乱语,但我仍然希望更有知识的人可以让我对此有更深入的了解。

The fact that strings are immutable is (among other things) a question of performance.字符串不可变的事实(除其他外)是一个性能问题。 This allows great optimizations, which are nice to have because strings are used a lot.这允许很大的优化,这是很好的,因为字符串被大量使用。

Incidentally, you can also have lists of characters, if you wanted to, so it is easy to have both mutable and immutable strings this way.顺便说一下,如果你愿意的话,你也可以有字符列表,所以通过这种方式很容易同时拥有可变和不可变字符串。 However, if strings were actually lists of characters, it would be harder in python to make what strings currently are, meaning it would be easy to have mutable strings, but hard to have immutable ones.然而,如果字符串实际上是字符列表,那么在 python 中将更难创建当前的字符串,这意味着可变字符串很容易,但不可变字符串很难。

As pointed out by a comment, this immutability is the reason why strings are not subclasses of lists.正如评论所指出的,这种不变性是字符串不是列表子类的原因。

An other reason is that the list class in python does not represent any sequential type, just what are usually called dynamic arrays in other languages.另一个原因是python中的list class不代表任何顺序类型,就是其他语言中通常所说的动态arrays。 For instance, functional programming languages usually call linked lists list .例如,函数式编程语言通常称为链表list This means that it's not just because a str can be viewed as a sequence type that it should inherit list .这意味着不仅仅是因为str可以被视为它应该继承list的序列类型。 However, this is still true: str , just as list , can be viewed as a sequence type, which is why it is an iterable .然而,这仍然是正确的: str ,就像list一样,可以被视为一个序列类型,这就是为什么它是一个iterable This kind of interface, in Python, does not work with subclassing, but just with duck-typing, so str does not need to inherit from any iterable super-class to be one (in particular, it needs not to inherit from list ).在 Python 中,这种接口不适用于子类化,而仅适用于鸭子类型,因此str不需要从任何iterable的超类继承成为一个(特别是,它不需要继承自list )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM