


Immutable vs. Mutable Types in Python: When Does Subclassing Break Immutability?
Immutable vs Mutable Types: A Deeper Understanding
The difference between immutable and mutable types can be a source of confusion, especially when it comes to certain classes that inherit from immutable types.
Immutable Types: Unchanging by Design
In Python, immutable types are objects whose value cannot be modified in place. Once created, an immutable object remains unchanged; any attempt to modify it results in a new object. For example, the float object is immutable, meaning that it cannot be altered directly.
SubclassingImmutable Types: Creating the Illusion of Mutability
However, it is possible to create subclasses of immutable types that appear to be mutable. This is achieved by overriding the __new__ method. For instance, the RoundFloat class is a subclass of float that rounds its value to two decimal places:
class RoundFloat(float): def __new__(cls, val): return float.__new__(cls, round(val, 2))
While this code defines a new class that inherits from float, the RoundFloat object remains immutable. This is because the __new__ method simply creates a new float object with the rounded value, and it does not alter the original float object.
Mutable Types: Changing on the Inside
In contrast, mutable types allow their values to be modified directly. Classes that define methods can be considered mutable. For example, the SortedKeyDict class inherits from dict and defines an example() method:
class SortedKeyDict_a(dict): def example(self): return self.keys()
This class allows the modification of its values within the provided methods. However, it's important to note that the SortedKeyDict class itself is still immutable. Its values can be changed, but the underlying instance remains the same.
Understanding Mutability in Practice
To better understand the difference between immutable and mutable types, consider the following scenario. Passing the set d to the SortedKeyDict class with __new__ raises an error, while passing it to the RoundFloat class with __new__ does not.
d = (('zheng-cai', 67), ('hui-jun', 68),('xin-yi', 2)) SortedKeyDict.__new__(cls, d) # Error raised RoundFloat.__new__(cls, 12) # No error
This illustrates that SortedKeyDict is mutable and RoundFloat is immutable. Because SortedKeyDict is mutable, it can be modified in place within its methods. In contrast, RoundFloat is immutable, so passing it to __new__ does not modify the original object.
The above is the detailed content of Immutable vs. Mutable Types in Python: When Does Subclassing Break Immutability?. For more information, please follow other related articles on the PHP Chinese website!

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

NumPyallowsforvariousoperationsonarrays:1)Basicarithmeticlikeaddition,subtraction,multiplication,anddivision;2)Advancedoperationssuchasmatrixmultiplication;3)Element-wiseoperationswithoutexplicitloops;4)Arrayindexingandslicingfordatamanipulation;5)Ag

ArraysinPython,particularlythroughNumPyandPandas,areessentialfordataanalysis,offeringspeedandefficiency.1)NumPyarraysenableefficienthandlingoflargedatasetsandcomplexoperationslikemovingaverages.2)PandasextendsNumPy'scapabilitieswithDataFramesforstruc

ListsandNumPyarraysinPythonhavedifferentmemoryfootprints:listsaremoreflexiblebutlessmemory-efficient,whileNumPyarraysareoptimizedfornumericaldata.1)Listsstorereferencestoobjects,withoverheadaround64byteson64-bitsystems.2)NumPyarraysstoredatacontiguou

ToensurePythonscriptsbehavecorrectlyacrossdevelopment,staging,andproduction,usethesestrategies:1)Environmentvariablesforsimplesettings,2)Configurationfilesforcomplexsetups,and3)Dynamicloadingforadaptability.Eachmethodoffersuniquebenefitsandrequiresca

The basic syntax for Python list slicing is list[start:stop:step]. 1.start is the first element index included, 2.stop is the first element index excluded, and 3.step determines the step size between elements. Slices are not only used to extract data, but also to modify and invert lists.

Listsoutperformarraysin:1)dynamicsizingandfrequentinsertions/deletions,2)storingheterogeneousdata,and3)memoryefficiencyforsparsedata,butmayhaveslightperformancecostsincertainoperations.

ToconvertaPythonarraytoalist,usethelist()constructororageneratorexpression.1)Importthearraymoduleandcreateanarray.2)Uselist(arr)or[xforxinarr]toconvertittoalist,consideringperformanceandmemoryefficiencyforlargedatasets.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1
Powerful PHP integrated development environment
