重写内置类 (Python)
如何查看和覆盖内置类的完整定义?我已经看过库文档,但我正在寻找更多内容。
例如,是否可以重写 Array 类,使基索引从 1 而不是 0 开始,或者将列表的 .sort()
重写为我自己喜欢的排序算法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要创建您自己的
sort()
方法,就这么简单:我不建议更改列表的索引方式,因为这违背了最佳实践,所以我什至没有提供一个示例!每当你想打破运算符重载或索引之类的约定时,我觉得你应该重新思考为什么要这样做并适应约定。
For creating your own
sort()
method, it's as simple as this: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.
您可以继承内置类型并覆盖或添加行为。如果您应该这样做,那就完全是另一个问题了。对于基于 n 的列表的实现(例如从 1 开始)请参阅此链接(数组应该非常相似)。
对于排序,您可以简单地使用
sorted
上的键函数。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
.