4

Possible Duplicate:
Can I add custom methods/attributes to built-in Python types?

Throughout using Python I have seen many things that can be used on strings such as .lower() or .startswith() or .endswith(), however, I am unsure on how to make functions that act similar to it, as what I thought of would have to use a class that passes the string to the function, and I simply want to do something like "the string".myfunc() instead of MyClassObjWithString.myfunc().

Is there any way to make functions like this?

Community
  • 1
  • 1
IT Ninja
  • 6,174
  • 10
  • 42
  • 65

3 Answers3

6

In python, string literals are always of type basestring (or str in py3k). As such, you can't add methods to string literals. You can create a class which accepts a string in the constructor and has methods which might be useful:

MyClass("the string").myfunc()

Of course, then it would probably be argued that you should be writing a function:

myfunc("the string")
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • So, I take it python doesn't have any 'prototype' mechanism a-la javascript that would let you overright/extend basestring (right?). But can you have MyClass derive from basicstring, so all methods available in basicstring will be available as well. e.g. MyClass("the string").lower()? – Uri London Oct 25 '12 at 19:52
  • 1
    @Uri -- That is correct. – mgilson Oct 25 '12 at 19:54
  • apology, my second question was NOT a yes/no question (although it was worded this way). Can you please point me HOW to inherit from basicstring. – Uri London Oct 25 '12 at 21:13
  • 1
    `class MyString(basestring): pass` -- If you're just working with ascii, then `class MyString(str): pass` is probably easier. See the link that was posted as a possible duplicate on the question as well. There's an exmple there. – mgilson Oct 25 '12 at 21:16
1

You cannot write a function with which you can do

"the string".myfunc()

because that would mean modifying the string class. But why not just write a method with which you could do

myfunc("the string")

Something like

def myfunc(s):
   return s * 2
arshajii
  • 127,459
  • 24
  • 238
  • 287
0

These are methods and while you can add or replace methods to (some) classes after they have been defined - a practice called monkey-patching - it is highly discouraged and not possible with builtin classes.

Just use a function.

DasIch
  • 2,549
  • 1
  • 15
  • 23