How to prevent a method from being overridden in Python?
Jul 13, 2025 am 02:56 AMIn 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.
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
.

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.

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 overrideBase.__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.

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!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The key to dealing with API authentication is to understand and use the authentication method correctly. 1. APIKey is the simplest authentication method, usually placed in the request header or URL parameters; 2. BasicAuth uses username and password for Base64 encoding transmission, which is suitable for internal systems; 3. OAuth2 needs to obtain the token first through client_id and client_secret, and then bring the BearerToken in the request header; 4. In order to deal with the token expiration, the token management class can be encapsulated and automatically refreshed the token; in short, selecting the appropriate method according to the document and safely storing the key information is the key.

To test the API, you need to use Python's Requests library. The steps are to install the library, send requests, verify responses, set timeouts and retry. First, install the library through pipinstallrequests; then use requests.get() or requests.post() and other methods to send GET or POST requests; then check response.status_code and response.json() to ensure that the return result is in compliance with expectations; finally, add timeout parameters to set the timeout time, and combine the retrying library to achieve automatic retry to enhance stability.

In Python, variables defined inside a function are local variables and are only valid within the function; externally defined are global variables that can be read anywhere. 1. Local variables are destroyed as the function is executed; 2. The function can access global variables but cannot be modified directly, so the global keyword is required; 3. If you want to modify outer function variables in nested functions, you need to use the nonlocal keyword; 4. Variables with the same name do not affect each other in different scopes; 5. Global must be declared when modifying global variables, otherwise UnboundLocalError error will be raised. Understanding these rules helps avoid bugs and write more reliable functions.

To create modern and efficient APIs using Python, FastAPI is recommended; it is based on standard Python type prompts and can automatically generate documents, with excellent performance. After installing FastAPI and ASGI server uvicorn, you can write interface code. By defining routes, writing processing functions, and returning data, APIs can be quickly built. FastAPI supports a variety of HTTP methods and provides automatically generated SwaggerUI and ReDoc documentation systems. URL parameters can be captured through path definition, while query parameters can be implemented by setting default values ??for function parameters. The rational use of Pydantic models can help improve development efficiency and accuracy.

Add timeout control to Python's for loop. 1. You can record the start time with the time module, and judge whether it is timed out in each iteration and use break to jump out of the loop; 2. For polling class tasks, you can use the while loop to match time judgment, and add sleep to avoid CPU fullness; 3. Advanced methods can consider threading or signal to achieve more precise control, but the complexity is high, and it is not recommended for beginners to choose; summary key points: manual time judgment is the basic solution, while is more suitable for time-limited waiting class tasks, sleep is indispensable, and advanced methods are suitable for specific scenarios.

How to efficiently handle large JSON files in Python? 1. Use the ijson library to stream and avoid memory overflow through item-by-item parsing; 2. If it is in JSONLines format, you can read it line by line and process it with json.loads(); 3. Or split the large file into small pieces and then process it separately. These methods effectively solve the memory limitation problem and are suitable for different scenarios.

In Python, the method of traversing tuples with for loops includes directly iterating over elements, getting indexes and elements at the same time, and processing nested tuples. 1. Use the for loop directly to access each element in sequence without managing the index; 2. Use enumerate() to get the index and value at the same time. The default index is 0, and the start parameter can also be specified; 3. Nested tuples can be unpacked in the loop, but it is necessary to ensure that the subtuple structure is consistent, otherwise an unpacking error will be raised; in addition, the tuple is immutable and the content cannot be modified in the loop. Unwanted values can be ignored by \_. It is recommended to check whether the tuple is empty before traversing to avoid errors.

Python default parameters are evaluated and fixed values ??when the function is defined, which can cause unexpected problems. Using variable objects such as lists as default parameters will retain modifications, and it is recommended to use None instead; the default parameter scope is the environment variable when defined, and subsequent variable changes will not affect their value; avoid relying on default parameters to save state, and class encapsulation state should be used to ensure function consistency.
