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?

0

3 Answers 3

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")
Sign up to request clarification or add additional context in comments.

4 Comments

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 -- That is correct.
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.
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.
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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.