Re: Add methods to string objects.
- From: Magnus Lycka <lycka@xxxxxxxxx>
- Date: Thu, 30 Jun 2005 14:40:09 +0200
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!=x.upper(), self)
.... def uppers(self):
.... return filter(lambda x:x!=x.lower(), self)
....
>>> s = S('Hello World!')
>>> print s.uppers()
HW
>>> print s.lowers()
elloorldThis 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). .
- References:
- Add methods to string objects.
- From: Negroup
- Add methods to string objects.
- Prev by Date: RE: Store multiple dictionaries in a file
- Next by Date: Re: map vs. list-comprehension
- Previous by thread: Re: Add methods to string objects.
- Next by thread: Control Printer Queue On Windows 2000/XP
- Index(es):
Relevant Pages
|