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:
# 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'
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3