Extension of Built-in Python Types with Custom Methods and Attributes
In Python, you may encounter scenarios where you desire to extend built-in types with additional methods or attributes. However, directly altering these types is not permissible.
For instance, if you attempt to add a helloWorld() method to the dict type as demonstrated in JavaScript, you will find that such an approach is not supported.
Workaround Using Subclassing and Namespace Substitution
While you cannot directly augment the original type, there exists a clever workaround. By subclassing the target type and subsequently substituting it within the built-in/global namespace, you can effectively mimic the desired behavior.
Here's an implementation in Python:
<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()) # 14 print(str(0).first_last()) # 00 print(str('').first_last()) # '' # Note that objects created by literal syntax will not have the extended methods print('0'.first_last()) # AttributeError: 'str' object has no attribute 'first_last'</code>
In this example, the mystr subclass extends the str type by adding a first_last() method. The __builtin__.str assignment redirects all built-in str calls to use the modified subclass instead. As a result, objects instantiated with the built-in str() constructor now possess the first_last() method.
However, it's crucial to note that objects created using literal syntax ('string') will remain instances of the unmodified str type and will not inherit the custom methods.
The above is the detailed content of How can I extend built-in Python types with custom methods and attributes?. For more information, please follow other related articles on the PHP Chinese website!