Creating the "string" .functions () python function

Possible duplicate:
Can I add my own methods / attributes to Python built-in types?

Throughout my use of Python, I have seen many things that can be used for strings, such as .lower() or .startswith() or .endswith() , however I'm not sure how to create functions that act similarly to it, like that I thought I would have to use a class that passes a string to the function, and I just want to do something like "the string".myfunc() instead of MyClassObjWithString.myfunc() .

Is there any way to make such functions?

+4
source share
3 answers

In python, string literals are always of type basestring (or str in py3k). Thus, you cannot add methods to string literals. You can create a class that takes a string in the constructor and has methods that can be useful:

 MyClass("the string").myfunc() 

Of course, then it could probably be argued that you should write a function:

 myfunc("the string") 
+6
source

You cannot write a function with which you can do

 "the string".myfunc() 

because it means changing the class of strings. But why not just write a method with which you could do

 myfunc("the string") 

Sort of

 def myfunc(s): return s * 2 
+1
source

These are methods, and while you can add or replace methods (some) of the classes after they have been defined - a practice called monkey patches - it is very discouraged and impossible with built-in classes.

Just use the function.

0
source

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


All Articles