开发者

Location of python string class in the source code

I'm looking into overloading the + operator for a certain string so I was thinking of su开发者_JS百科bclassing 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.


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.


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'


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'


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜