views:

184

answers:

2

How can I view and override the full definition for built in classes? I have seen the library docs but am looking for something more.

For e.g. is it possible to override the Array Class such that the base index starts from 1 instead of 0, or to override .sort() of list to a sorting algorithm of my own liking?

+2  A: 

You can inherit from builtin types and override or add behaviour. If you should do this is an other question altogether. For an implementation of an n-based list (starting at 1 for example) see this link (Array should be very similar).

For sort you can simply use the key function on sorted.

ChristopheD
Thanks that was helpful.
Yipeng
+6  A: 

For creating your own sort() method, it's as simple as this:

class MyList(list):
    def sort(self):
       return 'custom sorting algorithm'

mylist = MyList([1,2,3])
mylist.sort() # => 'custom sorting algorithm'

I would NOT recommend changing the way lists are indexed as that goes against best practices, so I'm not even providing an example of that! Whenever you want to break convention for things like operator overloading or indexing, I feel that you should rethink why you want to do that and adapt to convention.

jathanism
Thanks that was helpful.
Yipeng
I can understand that it is not recommended... But I just wanted to know whether (and how) it could be done.
Yipeng
What you are looking for would be to overload `__getitem__` in your subclass: http://docs.python.org/reference/datamodel.html#object.__getitem__
jathanism