Location of python string class in the source code

Question:

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.

Asked By: momo

||

Answers:

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.

Answered By: Matthew Flaschen

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'
Answered By: S.Lott

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'
Answered By: momo

This appears to be a link that is not currently dead in 2020: https://svn.python.org/projects/python/trunk/Objects/stringobject.c

Answered By: Justin Furuness
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.