Custom String Method Implementation

How to add custom method to python inline data type? For example, I would like to implement one of the solutions to this question , but to be able to call it as follows:

>>> s = "A string with extra whitespace" >>> print s.strip_inner() >>> A string with extra whitespace 

So, how would you define a custom .strip_inner() string method?

+7
source share
3 answers

You can not. And you do not need.

See Extending built-in classes in python for an alternative solution. A subclass is the way here.

+5
source

C has built-in classes such as str , so you cannot control them. Instead, you can 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 
+2
source

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

If you need polymorphism, 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
source

All Articles