473,503 Members | 1,655 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Add methods to string objects.

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.
Jul 19 '05 #1
5 13121
ne*****@gmail.com (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
Jul 19 '05 #2
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()

Jul 19 '05 #3
In article <11**********************@z14g2000cwz.googlegroups .com>,
"si*************@gmail.com" <si*************@gmail.com> 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?
Jul 19 '05 #4
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()

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).
Jul 19 '05 #5
Roy Smith wrote:
In article <11**********************@z14g2000cwz.googlegroups .com>,
"si*************@gmail.com" <si*************@gmail.com> 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.
Jul 19 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

18
6934
by: John M. Gabriele | last post by:
I've done some C++ and Java in the past, and have recently learned a fair amount of Python. One thing I still really don't get though is the difference between class methods and instance methods. I...
22
12001
by: Generic Usenet Account | last post by:
A lot has been said in this newsgroup regarding the "evil" set/get accessor methods. Arthur Riel, (of Vanguard Training), in his class, "Heuristis for O-O Analysis & Design", says that there is...
9
2644
by: Laban | last post by:
Hi, I find myself using static methods more than I probably should, so I am looking for some advice on a better approach. For example, I am writing an app that involves quite a bit of database...
14
6288
by: Joe Fallon | last post by:
I am trying to build a Data Access Layer for a SQL Server back end. My class has a number of methods in it. The constructor takes a connection string. I currently have to instantiate an object...
32
2343
by: Tubs | last post by:
Am i missing something or does the .Net Framework have a quirk in the way methods work on an object. In C++ MFC, if i have a CString and i use the format method, i format the string i am using. ...
10
1732
by: John | last post by:
Trying to find out what is essential / optional, I made an extremely simple Class and Module combination to add two numbers. (see below) It appears that an empty constructor is needed n order to...
15
2144
by: dn | last post by:
I'm starting an n-tier application with an ASP.NET 2.0 presentation layer, a business layer, a data access layer, and a SQL Server 2005 database, and I have a question. In the business and data...
12
5505
by: Andrew Poulos | last post by:
With the following code I can't understand why this.num keeps incrementing each time I create a new instance of Foo. For each instance I'm expecting this.num to alert as 1 but keeps incrementing. ...
10
104978
by: r035198x | last post by:
The Object class has five non final methods namely equals, hashCode, toString, clone, and finalize. These were designed to be overridden according to specific general contracts. Other classes that...
2
1764
by: fgh.vbn.rty | last post by:
Hi, I'm not sure if i'm asking the question correctly but anyway here it is. Say I have 3 classes - class A, class B, class R. 1) A and B are the building blocks and R is like a repository...
0
7202
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7086
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
6991
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5578
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
3167
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3154
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1512
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
736
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
380
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.