Add methods to string objects.
roccomoretti at hotpop.com
Thu Jun 30 15:31:53 CEST 2005
Roy Smith wrote:
> In article <1120134661.407265.251710 at z14g2000cwz.googlegroups.com>,
> "simon.dahlbacka at gmail.com" <simon.dahlbacka at gmail.com> wrote:
>>You can even get closer, but it is NOT recommended
>> def plural (self):
>> if self.value[-1] in "sz":
>> return self.value + "es"
>> return self.value + "s"
>>setattr(__builtins__, "str", foostr)
>># 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
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.
More information about the Python-list