Home >Backend Development >Python Tutorial >## Can You Enhance Python\'s Built-in Types with Custom Methods and Attributes?
Can Custom Methods and Attributes Be Added to Built-in Python Types?
In Python, it is not possible to directly modify the built-in data types such as dicts. However, a technique known as "monkey patching" allows a subclass to be created and substituted into the global namespace. This provides an enhanced version of the original data type.
Monkey Patching Technique
Example: Adding a first_last() Method to str
<code class="python"># Built-in namespace import __builtin__ # Extended subclass class mystr(str): def first_last(self): if self: return self[0] + self[-1] else: return '' # Substitute the original str with the subclass on the built-in namespace __builtin__.str = mystr print(str(1234).first_last()) # Output: 14 print(str(0).first_last()) # Output: 00 print(str('').first_last()) # Output: ''</code>
Limitations:
This technique has a few caveats:
The above is the detailed content of ## Can You Enhance Python\'s Built-in Types with Custom Methods and Attributes?. For more information, please follow other related articles on the PHP Chinese website!