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.
The source for python 2.7 itself can be found at http://hg.python.org/cpython. Other versions of python have had their source imported onto Launchpad. You can see them here. Click on one you want to see and you can then click "Browse the Code".
Python has a built-in string class named "str" with many handy features (there is an older module named "string" which you should not use). String literals can be enclosed by either double or single quotes, although single quotes are more commonly used.
We use the getsource() method of inspect module to get the source code of the function. Returns the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With