Table of Contents
Name overwriting is achieved using double underscore prefix (Name Mangling)
Throw exception directly in the method
Simulate final method using decorator
Tips: Use property alternatives
Home Backend Development Python Tutorial How to prevent a method from being overridden in Python?

How to prevent a method from being overridden in Python?

Jul 13, 2025 am 02:56 AM
python Method overriding

In Python, although there is no built-in final keyword, it can simulate unsurpassable methods through name rewriting, runtime exceptions, decorators, etc. 1. Use a double underscore prefix to trigger name override, making it difficult for subclasses to override methods; 2. Use a custom decorator to determine the caller type and throw an exception to prevent subclass redefinition; 3. Use a custom decorator to mark the method as final and check it in combination with metaclasses or class decorators; 4. The behavior can be encapsulated as property attributes to reduce the possibility of being modified. These methods provide varying degrees of protection, but none of them completely restrict the coverage behavior.

How to prevent a method from being overridden in Python?

In Python, by default, the class methods can be overwritten by subclasses. If you want a method to not be overwritten, the most direct way is to achieve "unoverwritten" effects through naming conventions and design patterns, because Python itself does not have keywords like Java's final or C#'s sealed .

How to prevent a method from being overridden in Python?

Here are some common practices:


Name overwriting is achieved using double underscore prefix (Name Mangling)

Python provides a mechanism called "Name Mangling". When you precede two underscores (such as __method_name ) of a class's method or property, Python will overwrite the name, making it harder to access or overwrite externally.

How to prevent a method from being overridden in Python?
 class Base:
    def __my_method(self):
        print("This is a private method")

    def call_my_method(self):
        self.__my_method()

class Derived(Base):
    def __my_method(self):
        print("Trying to override")

d = Derived()
d.call_my_method() # Output "This is a private method"

illustrate:

  • In fact, Derived.__my_method does not override Base.__my_method , but defines a new method.
  • Because Base.__my_method was renamed to _Base__my_method , there will be no conflict.
  • This approach is not to completely block coverage, but to make coverage more difficult.

Throw exception directly in the method

If you want to explicitly prohibit subclasses from overwriting a method at runtime, you can add judgment logic to the method. If you detect that the current class is not the original class that defines the method, an exception will be thrown.

How to prevent a method from being overridden in Python?
 class Base:
    def my_method(self):
        if type(self) != Base:
            raise TypeError("my_method cannot be overridden")
        print("Original implementation")

class Derived(Base):
    def my_method(self):
        print("Trying to override")

Use scenarios:

  • Suitable for situations where you want to find problems during the development or debugging phase.
  • The disadvantage is that an error will only be reported when the method is called, and the error cannot be discovered in advance.

Simulate final method using decorator

You can customize a decorator to mark certain methods as "not overridable", and implement final -like functionality by checking whether the methods have been redefined.

 def final(method):
    setattr(method, '__is_final__', True)
    Return method

class Base:
    @final
    def my_method(self):
        print("This is a final method")

class Derived(Base):
    def my_method(self):
        print("Trying to override")

Then you can combine metaclasses or class decorators to check whether the final convention is violated.

Advantages of this method:

  • More flexible, and the rules can be customized according to project needs.
  • Illegal overwrite behavior can be detected when the class is defined.

But some additional auxiliary code is required to implement the full functionality.


Tips: Use property alternatives

If you do not want a behavior to be modified, you can also consider encapsulating it into a read-only property property.

 class Base:
    @property
    def status(self):
        return "original"

class Derived(Base):
    @property
    def status(self):
        return "overridden" # will still be overwritten

However, this method cannot really prevent coverage, it just provides an idea.


In general, Python is a language that emphasizes "trust programmers" and does not encourage coercive restrictions on certain behaviors. But in actual development, if you do have the need to prevent methods from being covered, you can achieve "soft limitations" through the above methods.

Basically these methods are all. Although they cannot be completely "sealed", they are enough in most cases.

The above is the detailed content of How to prevent a method from being overridden in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is a pure function in Python What is a pure function in Python Jul 14, 2025 am 12:18 AM

Pure functions in Python refer to functions that always return the same output with no side effects given the same input. Its characteristics include: 1. Determinism, that is, the same input always produces the same output; 2. No side effects, that is, no external variables, no input data, and no interaction with the outside world. For example, defadd(a,b):returna b is a pure function because no matter how many times add(2,3) is called, it always returns 5 without changing other content in the program. In contrast, functions that modify global variables or change input parameters are non-pure functions. The advantages of pure functions are: easier to test, more suitable for concurrent execution, cache results to improve performance, and can be well matched with functional programming tools such as map() and filter().

How to prevent a method from being overridden in Python? How to prevent a method from being overridden in Python? Jul 13, 2025 am 02:56 AM

In Python, although there is no built-in final keyword, it can simulate unsurpassable methods through name rewriting, runtime exceptions, decorators, etc. 1. Use double underscore prefix to trigger name rewriting, making it difficult for subclasses to overwrite methods; 2. judge the caller type in the method and throw an exception to prevent subclass redefinition; 3. Use a custom decorator to mark the method as final, and check it in combination with metaclass or class decorator; 4. The behavior can be encapsulated as property attributes to reduce the possibility of being modified. These methods provide varying degrees of protection, but none of them completely restrict the coverage behavior.

Can a Python class have multiple constructors? Can a Python class have multiple constructors? Jul 15, 2025 am 02:54 AM

Yes,aPythonclasscanhavemultipleconstructorsthroughalternativetechniques.1.Usedefaultargumentsinthe__init__methodtoallowflexibleinitializationwithvaryingnumbersofparameters.2.Defineclassmethodsasalternativeconstructorsforclearerandscalableobjectcreati

Python for loop range Python for loop range Jul 14, 2025 am 02:47 AM

In Python, using a for loop with the range() function is a common way to control the number of loops. 1. Use when you know the number of loops or need to access elements by index; 2. Range(stop) from 0 to stop-1, range(start,stop) from start to stop-1, range(start,stop) adds step size; 3. Note that range does not contain the end value, and returns iterable objects instead of lists in Python 3; 4. You can convert to a list through list(range()), and use negative step size in reverse order.

Accessing data from a web API in Python Accessing data from a web API in Python Jul 16, 2025 am 04:52 AM

The key to using Python to call WebAPI to obtain data is to master the basic processes and common tools. 1. Using requests to initiate HTTP requests is the most direct way. Use the get method to obtain the response and use json() to parse the data; 2. For APIs that need authentication, you can add tokens or keys through headers; 3. You need to check the response status code, it is recommended to use response.raise_for_status() to automatically handle exceptions; 4. Facing the paging interface, you can request different pages in turn and add delays to avoid frequency limitations; 5. When processing the returned JSON data, you need to extract information according to the structure, and complex data can be converted to Data

python one line if else python one line if else Jul 15, 2025 am 01:38 AM

Python's onelineifelse is a ternary operator, written as xifconditionelsey, which is used to simplify simple conditional judgment. It can be used for variable assignment, such as status="adult"ifage>=18else"minor"; it can also be used to directly return results in functions, such as defget_status(age):return"adult"ifage>=18else"minor"; although nested use is supported, such as result="A"i

How to read a JSON file in Python? How to read a JSON file in Python? Jul 14, 2025 am 02:42 AM

Reading JSON files can be implemented in Python through the json module. The specific steps are: use the open() function to open the file, use json.load() to load the content, and the data will be returned in a dictionary or list form; if you process JSON strings, you should use json.loads(). Common problems include file path errors, incorrect JSON format, encoding problems and data type conversion differences. Pay attention to path accuracy, format legality, encoding settings, and mapping of boolean values and null.

Python for loop to read file line by line Python for loop to read file line by line Jul 14, 2025 am 02:47 AM

Using a for loop to read files line by line is an efficient way to process large files. 1. The basic usage is to open the file through withopen() and automatically manage the closing. Combined with forlineinfile to traverse each line. line.strip() can remove line breaks and spaces; 2. If you need to record the line number, you can use enumerate(file, start=1) to let the line number start from 1; 3. When processing non-ASCII files, you should specify encoding parameters such as utf-8 to avoid encoding errors. These methods are concise and practical, and are suitable for most text processing scenarios.

See all articles