How to initialize instances of subclass of 'str'?

Kenneth McDonald kenneth.m.mcdonald at sbcglobal.net
Sat Aug 7 00:17:03 EDT 2004


I'm attempting to create a subclass of 'str' that I can abitrarily
initialize at creation time. As an illustration, this gives the
flavor of what I'm trying to do:

class AlwaysLower(str):
   def __init__(self, s):
      str.__init__(self, s.lower())

The idea is that an AlwaysLower instance should be a string
which is always lowercase; AlwaysLower('A') -> 'a',
AlwaysLower('b') -> 'b', etc. (Of course, the resultant
instances are not _just_ strings, but since they are
subclasses of str, they can be treated and viewed as strings,
as I implicitly do above.)

Unfortunately, the above code doesn't work; the resultant
instance's string value is always s, i.e. the call to 
str.__init__ has no effect.

I realize that I could write a function to do this, but there
are other reasons I want to subclass str. I also realize
I could have a function call AlwaysLower with a lowercase
argument, but I find that inelegant.

I've also tried messing around with __new__, but
gotten only runtime exceptions for my troubles :-).
At the moment, what's really stumping me isn't so much
how to do this, but more the mechanism by which 's' is
being used to initialize the string. It's not being passed
by __init__, so how is it being passed? __new__? As
I say, I couldn't get anywhere with that.

Anyone know of good examples of how to subclass builtins?

Thanks,
Ken McDonald



More information about the Python-list mailing list