Implementing a custom string method

后端 未结 3 1313
余生分开走
余生分开走 2021-01-17 23:15

How do you add a custom method to a built-in python datatype? For example, I\'d like to implement one of the solutions from this question but be able to call it as follows:

相关标签:
3条回答
  • 2021-01-17 23:46

    The built-in classes such as str are implemented in C, so you can't manipulate them. What you can do, instead, is extend the str class:

    >>> class my_str(str):
    ...     def strip_inner(self):
    ...         return re.sub(r'\s{2,}', ' ', s)
    ... 
    >>> s = my_str("A   string  with extra   whitespace")
    >>> print s.strip_inner()
    A string with extra whitespace
    
    0 讨论(0)
  • 2021-01-18 00:01

    You can't. And you don't need to.

    See Extending builtin classes in python for an alternative solution. Subclassing is the way to go here.

    0 讨论(0)
  • 2021-01-18 00:05

    You can't add methods to built-in classes. But what's wrong with using functions? strip_inner(s) is just fine and pythonic.

    If you need polymorphism, then just use if isinstance(obj, type_) to determine what to do, or for something more extensible, use a generic function package, like PEAK-Rules.

    0 讨论(0)
提交回复
热议问题