On 21/12/19 2:50 pm, Greg Ewing wrote:
On 21/12/19 1:59 am, Stefan Ram wrote:
   I would like to add a method to a string.

   This is not possible in Python?

It's not possible. Built-in classes can't have methods added
to them.

You can define your own subclass of str and give it whatever
methods you want.

But in your case:

for s in 'abc'.like( '(.)' ):

I would recommend making it a stand-alone function instead,
so that you would write

   for s in like('abc', '(.)'):


Contrarily: sub-classing str and making like() a method strikes me as the way to go, particularly if the 'abc' disappears into the instance's __init__() - and better still if the '(.)' may also be absorbed as a class/instance attribute, and even more-so if like() is not the only method/stand-alone function required for this category of strings...

but...

choose a self-documenting name for the class, and
choose a better-documenting name for the method.

instance = class( "abc" )
...
for s in instance.method():

is clean, self-documenting (or will be once you've done your thing), easier to test (fewer args => easier assured testing).

--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to