Extending built-in objects/classes

John Machin sjmachin at lexicon.net
Mon Jul 3 07:15:24 EDT 2006


On 3/07/2006 7:55 PM, Jon Clements wrote:
> cmdrrickhunter at yaho.com wrote:
>> My experiance is mostly with old-style classes, but here goes.
>>
>> first off, the <what> question is actually easier than you think.
>> After all, self is an instance of a string, so   self[3:4] would grab
>> the slice of characters between 3 and 4 =)
>>
> 
> That's kind of funky - I like it. However, I'd still like to know what
> <what> technically is - any ideas on how to find out?

You have already been told: you don't need "self.<what>", you just write 
"self" ... self *is* a reference to the instance of the mystr class that 
is being operated on by the substr method.

You did ask for criticism: here's what's intended to be constructive 
criticism: you can often find out answers a lot faster by actually 
trying it out yourself. E.g. do I need an __init__() method?

|>> class mystr(str):
...     def substr(self, start, length):
...         return self[start-1:start-1+length]
...
|>> foo = mystr('abcdef')
|>> foo
'abcdef'
|>> foo.substr(2, 3)
'bcd'
|>> mystr.substr(foo, 2, 3)
'bcd'

No __init__(), no <what>, it just works!

HTH,
John






More information about the Python-list mailing list