Location of python string class in the source code

2019-01-27 13:17发布

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.

3条回答
我命由我不由天
2楼-- · 2019-01-27 13:44

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.

查看更多
放荡不羁爱自由
3楼-- · 2019-01-27 13:55

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'
查看更多
淡お忘
4楼-- · 2019-01-27 14:01

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'
查看更多
登录 后发表回答