How to add my own method to str built-in type?

def change(s):
    result=""
    for index,item in enumerate(s):
        if(index%2 !=0): result=result+item
    return(result)

This function can extract all even-numbered characters from a string to a new line:

>>> x="hallo world"
>>> change(x)
'al ol'
  • How to do this in a class method str? When you type x.change()in the Python console, I get the same result as change(x). x.change()will receive 'al ol'.

  • dir(x)will get 'change'the output, for example:

    ['__add__', '__class__', ...omitted..., 'zfill', 'change'] 
    
+4
source share
1 answer

You cannot do this. Well, at least not directly. Python does not allow adding custom methods / attributes to built-in types. This is simply the law of language.

() str:

class MyStr(str):
    def change(self): # 's' argument is replaced by 'self'
        result=""
        for index,item in enumerate(self): # Use 'self' here instead of 's'
            if(index%2 !=0): result=result+item
        return(result)

:

>>> class MyStr(str):
...     def change(self):
...         result=""
...         for index,item in enumerate(self):
...             if(index%2 !=0): result=result+item
...         return(result)
...
>>> x = MyStr("hallo world")
>>> x
'hallo world'
>>> x.change()
'al ol'
>>> 'change' in dir(x)
True
>>>

MyStr str . , , str:

>>> x = MyStr("hallo world")
>>> x.upper()
'HALLO WORLD'
>>> x.split()
['hallo', 'world']
>>>

, MyStr change.

+5

Source: https://habr.com/ru/post/1570544/


All Articles