What are the purposes of introducing immutable objects in Python?
在任何语言中引入不可变对象有什么意义?在...we can’t change a string by assigning to one of its positions... But we can always build a new one and assign it to the same name. Does that betrays the purpose of immutability in functional paradigm, and aligns with imperative paradigm? But in imperative paradigm, implementing mutability in terms of immutability and reference model is inefficient.
这在实现中并不少见,实际上-C字符串的实现方式完全相同(可变引用不可变对象)。在
有些语言(如C)使用字符数组来表示字符串,实际上字符串的长度是可变的(但是每个字符都是可变的)。在
请记住,关于“不变性”有许多相互竞争的定义(我读了一篇文章,上面列出并解释了所有这些定义,但我现在找不到它)。例如,它是否意味着对可变对象的常量引用(浅不变性)?还是对一个不可变对象的常量引用(深度不变性)?甚至是对不可变对象的“非固定”引用?这实际上取决于您希望使不变性具有多大的“深度”,以及如何在不“破坏”向后兼容性的情况下实现它。(在向后兼容性问题上,注意C++、C、java、java等许多语言实际上必须为常数变量引入特殊的关键字,例如,在{中的{{CD1}},^ {< CD2}}中,f {,^ {CD3}}在C中)。在
另一点:许多语言(C、Python)都具有函数特性,而不一定是纯粹(甚至主要)函数性语言。很多时候(例如在C中),功能特性在技术上是对语言的新的补充,所以有些功能特性可能不会像您所希望的那样“纯粹”地实现函数样式,以保持向后兼容性。在
另外,允许多种范式的一部分后果是,你通常可以用并不总是完全健康的方式“混合”它们——从句法的角度来说,很难或不可能“禁止”范式混合。在What are the reason that some types are designed to use immutable objects (numbers, strings, tuples), while other types (lists, dictionaries, sets) use mutable objects, instead of all the types immutable or mutable?
因为Python是一种多范式语言。不可变的数据类型适合于函数式编程,但是通常您需要可变的数据类型来进行面向对象的编程。因此,语言必须具有适合两种范式的特征。正如official documentation on Python's functional features所述The designers of some computer languages choose to emphasize one particular approach to programming. This often makes it difficult to write programs that use a different approach. Other languages are multi-paradigm languages that support several different approaches. Lisp, C++, and Python are multi-paradigm; you can write programs or libraries that are largely procedural, object-oriented, or functional in all of these languages. In a large program, different sections might be written using different approaches; the GUI might be object-oriented while the processing logic is procedural or functional, for example.
因此,基本上,Python希望允许您选择自己的范例(甚至可以在同一个程序中混合它们)。这实际上是非常方便的-许多框架(例如.NET)正在鼓励它。(例如,WPF/XAML,倾向于鼓励gui的声明性范例)。在