Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Add methods to string objects.

Reply
Thread Tools

Add methods to string objects.

 
 
Negroup
Guest
Posts: n/a
 
      06-30-2005
Hi all.
I'm writing a simple Python module containing functions to process
strings in various ways. Actually it works importing the module that
contains the function I'm interested in, and calling
my_module.my_function('mystring').

I was just asking if it is possible to "extend" string objects'
behaviour so that it becomes possible to invoke something like
'anystring'.my_method().

1) does the latter approach bring some advantages?
2) how is it possible to achieve this goal?

Any pointer will be appreciated, thanks.
 
Reply With Quote
 
 
 
 
Roy Smith
Guest
Posts: n/a
 
      06-30-2005
http://www.velocityreviews.com/forums/(E-Mail Removed) (Negroup) wrote:
> I was just asking if it is possible to "extend" string objects'
> behaviour so that it becomes possible to invoke something like
> 'anystring'.my_method().


You can't quite do that, but you can get close. You can define your own
class which inherits from str, and then create objects of that class. For
example:

class myString (str):
def __init__ (self, value):
self.value = value

def plural (self):
if self.value[-1] in "sz":
return self.value + "es";
else:
return self.value + "s";

foo = myString("foo")
bar = myString("bar")
baz = myString("baz")

print foo.plural(), bar.plural(), baz.plural() # my defined method
print foo.capitalize() # inherited from base class
 
Reply With Quote
 
 
 
 
simon.dahlbacka@gmail.com
Guest
Posts: n/a
 
      06-30-2005
You can even get closer, but it is NOT recommended

class foostr(str):
def plural (self):
if self.value[-1] in "sz":
return self.value + "es"
else:
return self.value + "s"


#ugly hack
setattr(__builtins__, "str", foostr)

print str("apple").plural()

# this however does not work
# print "apple".plural()

 
Reply With Quote
 
Magnus Lycka
Guest
Posts: n/a
 
      06-30-2005
Negroup wrote:
> Hi all.
> I'm writing a simple Python module containing functions to process
> strings in various ways. Actually it works importing the module that
> contains the function I'm interested in, and calling
> my_module.my_function('mystring').
>
> I was just asking if it is possible to "extend" string objects'
> behaviour so that it becomes possible to invoke something like
> 'anystring'.my_method().


The proper way is to extend the string type by subclassing it:

class S(str):
def my_method(self):
...

Then you can do "S('anystring').my_method()" etc.

Example:

>>> class S(str):

.... def lowers(self):
.... return filter(lambda x!=x.upper(), self)
.... def uppers(self):
.... return filter(lambda x!=x.lower(), self)
....
>>> s = S('Hello World!')
>>> print s.uppers()

HW
>>> print s.lowers()

elloorld

This means that your additional behaviour isn't available to
plain string literals. You need to instanciate S objects. This
is much less confusing for other programmers who read your code
(or for yourself when you read it a few years from now).
 
Reply With Quote
 
Roy Smith
Guest
Posts: n/a
 
      06-30-2005
In article <(E-Mail Removed) .com>,
"(E-Mail Removed)" <(E-Mail Removed)> wrote:

> You can even get closer, but it is NOT recommended
>
> class foostr(str):
> def plural (self):
> if self.value[-1] in "sz":
> return self.value + "es"
> else:
> return self.value + "s"
>
>
> #ugly hack
> setattr(__builtins__, "str", foostr)
>
> print str("apple").plural()
>
> # this however does not work
> # print "apple".plural()


It's fascinating that the setattr() works (and I agree with you that it's a
bad idea), but given that it does work, why doesn't it work with a string
literal?
 
Reply With Quote
 
Rocco Moretti
Guest
Posts: n/a
 
      06-30-2005
Roy Smith wrote:
> In article <(E-Mail Removed) .com>,
> "(E-Mail Removed)" <(E-Mail Removed)> wrote:
>
>
>>You can even get closer, but it is NOT recommended
>>
>>class foostr(str):
>> def plural (self):
>> if self.value[-1] in "sz":
>> return self.value + "es"
>> else:
>> return self.value + "s"
>>
>>
>>#ugly hack
>>setattr(__builtins__, "str", foostr)
>>
>>print str("apple").plural()
>>
>># this however does not work
>># print "apple".plural()

>
>
> It's fascinating that the setattr() works (and I agree with you that it's a
> bad idea), but given that it does work, why doesn't it work with a string
> literal?


Because the string literal is the *actual* C-level builtin string type,
not whatever type happens to be in __builtins__.str at the time. ("At
the time" is also a tricky proposition - string literals are made into
obects at compile time, before __builtins__ is twiddled with.)

BTW, on setattr():

'''
setattr( object, name, value)

This is the counterpart of getattr(). The arguments are an object, a
string and an arbitrary value. The string may name an existing attribute
or a new attribute. The function assigns the value to the attribute,
provided the object allows it. For example, setattr(x, 'foobar', 123) is
equivalent to x.foobar = 123.
'''

i.e. '''setattr(__builtins__, "str", foostr)''' is the same as
'''__builtins__.str = foostr''', but I would agree that the setattr
gives more of a "black magic" warning.
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Is there a way to find the class methods of a class, just like'methods' finds the instance methods? Kenneth McDonald Ruby 5 09-26-2008 03:09 PM
Top-Up Methods - Finarea (Voipcheap, internetcalls, etc.) et. al., VOIP Services Question - Top-up Methods News Reader UK VOIP 0 04-10-2006 02:41 PM
Why Petshop Changed all static methods to instance methods when upgrading from version 3.0 to version 3.1? Neo ASP .Net 1 01-07-2005 01:46 AM
Derived methods hiding inherited methods Tron Thomas C++ 10 11-10-2004 09:32 AM
Re: Templates and friends and template methods with private methods. Buster Copley C++ 5 07-07-2003 12:50 AM



Advertisments