开发者

Overriding Built-in Classes (Python)

开发者 https://www.devze.com 2022-12-30 01:31 出处:网络
How can I view and override the full definition for built in classes? I have seen the lib开发者_StackOverflow社区rary docs but am looking for something more.

How can I view and override the full definition for built in classes? I have seen the lib开发者_StackOverflow社区rary 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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消