Overriding Built-in Classes (Python)
How can I view and override the complete definition for built-in classes? I saw docs in the library , but I was looking for something more.
For example, is it possible to override the array class so that the base index starts at 1 instead of 0, or override the .sort()
list into a sorting algorithm of my own liking?
a source to share
To create your own method, sort()
it's as easy as:
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 this is contrary to best practices, so I am not even an example of this! Whenever you want to break the convention for things like operator overloading or indexing, I feel like you should rethink why you want to do this and adapt to the convention.
a source to share
You can inherit from built-in types and override or add behavior. If you have to do this, that's a different question. For an n based list implementation (e.g. starting from 1) see this link (array should be very similar).
For sorting, you can simply use the key function on sorted
.
a source to share