Re: Add methods to string objects.



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.
.




Relevant Pages