Re: Add methods to string objects.
- From: Rocco Moretti <roccomoretti@xxxxxxxxxx>
- Date: Thu, 30 Jun 2005 08:31:53 -0500
Roy Smith wrote:
In article <1120134661.407265.251710@xxxxxxxxxxxxxxxxxxxxxxxxxxxx>, "simon.dahlbacka@xxxxxxxxx" <simon.dahlbacka@xxxxxxxxx> 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.
.
- References:
- Add methods to string objects.
- From: Negroup
- Re: Add methods to string objects.
- From: Roy Smith
- Re: Add methods to string objects.
- From: simon.dahlbacka@xxxxxxxxx
- Re: Add methods to string objects.
- From: Roy Smith
- Add methods to string objects.
- Prev by Date: Re: When someone from Britain speaks, Americans hear a "British accent"...
- Next by Date: Re: Modules for inclusion in standard library?
- Previous by thread: Re: Add methods to string objects.
- Next by thread: Re: Add methods to string objects.
- Index(es):
Relevant Pages
|