Home >Backend Development >Python Tutorial >How Can You Extend Python\'s Built-in Types with Custom Methods?

How Can You Extend Python\'s Built-in Types with Custom Methods?

Barbara Streisand
Barbara StreisandOriginal
2024-10-24 19:27:021080browse

How Can You Extend Python's Built-in Types with Custom Methods?

Extending Built-in Python Types with Custom Methods

In Python, the built-in types such as dict and str are immutable and don't allow direct method additions. However, it's possible to achieve similar functionality by subclassing the built-in type and replacing it in the global namespace.

For instance, suppose you want to add a helloWorld() method to the dict type. While this is not feasible with direct modification, you can subclass dict and define the method in the subclass:

class MyDict(dict):
    def helloWorld(self):
        print("Hello world!")

To apply this subclass to all future dictionaries, substitute the original dict type in the built-in namespace:

import __builtin__
__builtin__.dict = MyDict

Now, any dictionary created will be of the MyDict type and have the helloWorld() method:

my_dict = {}
my_dict.helloWorld()  # Prints "Hello world!"

However, note that objects created through literal syntax (e.g., {}) will still be of the vanilla dict type and won't have the custom method:

vanilla_dict = {}
vanilla_dict.helloWorld()  # AttributeError: 'dict' object has no attribute 'helloWorld'

This approach provides a way to extend built-in types with custom methods, but it's not without its limitations. For example, literal syntax objects remain vanilla, and subclasses don't inherit any custom attributes or methods added to the parent type.

The above is the detailed content of How Can You Extend Python\'s Built-in Types with Custom Methods?. 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