Home >Backend Development >Python Tutorial >Immutable vs. Mutable Types: What's the Difference in Their Operability?
Immutable vs Mutable Types
In programming, types refer to the category or data structure to which a variable belongs. These types can be classified as immutable or mutable based on how they can be modified.
Immutable Types
Immutable types do not allow the modification of their contents once assigned. Instead, they replace themselves with a new object containing the updated data. Float is an example of an immutable type. For instance, creating a new subclass of float called RoundFloat, as seen in the provided code, does not change the immutability of the type. This is because the new method is responsible for creating new instances of the object and does not modify the existing object.
Mutable Types
Mutable types, on the other hand, can modify their contents in-memory. This allows the original reference to point to the updated object. In the provided example, SortedKeyDict_a is a mutable type because it includes methods that operate on the object, like example(). These methods can change the state of the object without creating a new one.
Operability
Regarding the tests performed on SortedKeyDict and RoundFloat, the difference lies in their behavior with the given set values. SortedKeyDict, being mutable, allows modifications without explicitly invoking the example() method. It sorts the keys internally and returns a dictionary. RoundFloat, however, does not support this behavior because it is immutable. As a result, attempting to pass integers to RoundFloat without invoking new flags an error.
The above is the detailed content of Immutable vs. Mutable Types: What's the Difference in Their Operability?. For more information, please follow other related articles on the PHP Chinese website!