views:

54

answers:

3

I'm looking into overloading the '+' operator for a certain string so I was thinking of subclassing the string class then adding the code in the new class. However I wanted to take a look at the standard string class first but I can't seem to find it... stupid eh?

Can anyone point the way? Even online documentation of the source code.

+1  A: 

It's documented here. The main implementation is in Objects/stringobject.c. Subclassing str probably isn't what you want, though. I would tend to prefer composition here; have an object with a string field, and special behavior.

Matthew Flaschen
A: 

You might mean this.

class MyCharacter( object ):
    def __init__( self, aString ):
        self.value= ord(aString[0])
    def __add__( self, other ):
        return MyCharacter( chr(self.value + other) )
    def __str__( self ):
        return chr( self.value )

It works like this.

>>> c= MyCharacter( "ABC" )
>>> str(c+2)
'C'
>>> str(c+3)
'D'
>>> c= c+1
>>> str(c)
'B'
S.Lott
A: 

my implementation is similar, though not as neat:

class MyClass:
    def __init__(self, name):
        self.name = name
    def __add__(self, other):
        for x in range(1, len(self.name)):
            a = list(self.name)[-1 * x]
            return self.name[:len(self.name)-x] + chr(ord(a) + other)


>>> CAA = MyClass('CAA')
>>> CAA + 1
'CAB'
>>> CAA + 2
'CAC'
>>> CAA + 15
'CAP'
momo
"not as neat"? It's got weird, weird problems. Why is there a `return` in the middle of of the `for` loop? That will perform the "loop" exactly once and stop. There's no actual "loop" going on. This can be simplified considerably.
S.Lott
Also, unless you're using Python 3, please make it a subclass of `object`.
S.Lott