search
HomeBackend DevelopmentPython TutorialImmutable vs. Mutable Types in Python: When Does Subclassing Break Immutability?

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you slice a Python list?How do you slice a Python list?May 02, 2025 am 12:14 AM

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

What are some common operations that can be performed on NumPy arrays?What are some common operations that can be performed on NumPy arrays?May 02, 2025 am 12:09 AM

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

How are arrays used in data analysis with Python?How are arrays used in data analysis with Python?May 02, 2025 am 12:09 AM

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

How does the memory footprint of a list compare to the memory footprint of an array in Python?How does the memory footprint of a list compare to the memory footprint of an array in Python?May 02, 2025 am 12:08 AM

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

How do you handle environment-specific configurations when deploying executable Python scripts?How do you handle environment-specific configurations when deploying executable Python scripts?May 02, 2025 am 12:07 AM

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

How do you slice a Python array?How do you slice a Python array?May 01, 2025 am 12:18 AM

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.

Under what circumstances might lists perform better than arrays?Under what circumstances might lists perform better than arrays?May 01, 2025 am 12:06 AM

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

How can you convert a Python array to a Python list?How can you convert a Python array to a Python list?May 01, 2025 am 12:05 AM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

DVWA

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

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

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

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment