Python 中有 sorted() 的神奇方法吗? [英] is there a magic method for sorted() in Python?

查看:47
本文介绍了Python 中有 sorted() 的神奇方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道python中有一些魔法方法可以被类覆盖,以控制某些内置函数处理这些类成员的方式.例如,len()str() 的行为可以通过魔术方法 __len__()__str__() 覆盖:

class EmptySet(object):def __len__(self):返回 0def __str__(self):返回 '​​[]'>>>e = EmptySet()>>>字符串(e)[]>>>长度(e)0

还有 __cmp__()__ge__(), __le__() 等方法来控制如何比较这些对象以及如何进行比较它们的列表应该由 list.sort() 排序.我的问题不是关于自定义列表中对象的顺序,而是关于对象本身的排序.假设集合不为空,我想使用 sorted() 对其进行排序:

class SetOfTwo(object):def __init__(self, a, b):el_0 = 一个el_1 = bdef __len__(self):返回 2def __str__(self):返回 '​​[{}, {}]'.format(el_0, el_1)

是否有一种神奇的方法可以让 sorted() 如果元素不按顺序翻转元素?我正在想象以下行为:

<预><代码>>>>s = SetOfTwo(2, 1)>>>字符串[2, 1]>>>t = 已排序>>>str(t)[1, 2]>>>类型(t)>>>两人组

解决方案

你绝对应该阅读 有关如何模拟容器类型的官方文档.基本上,一个应该作为容器(列表、字典等)工作的类需要实现方法来设置或获取成员 __getitem__()__setitem__() 并迭代项目__iter__() 并获取项目数 - 方法 __len__().这是最低要求.但是你也可以添加删除项目等操作的能力.

sorted() 内置函数的行为是迭代容器的元素并使用您提到的方法比较它们__cmp__(), __ge__(), __le__() 应该为项目而不是您已经知道的容器定义.然后创建一个新的 list 实例,其中的项目已排序,并返回这个新实例.你可以将它传递给你的自定义容器的构造函数,或者你可以用一个自定义函数包裹 sorted() ,该函数将返回所需的类实例.

I understand that there are magic methods in python that can be overwritten by classes to control the way certain built in functions treat the members of these classes. For example, the behavior of len() and str() can be overwritten via magic methods __len__() and __str__():

class EmptySet(object):
    def __len__(self):
        return 0

    def __str__(self):
        return '[]'

>>> e = EmptySet()
>>> str(e)
[]

>>> len(e)
0

There are also __cmp__() and __ge__(), __le__() etc methods to control how these objects can be compared and how a list of them should be ordered by list.sort(). My question is not about customizing the ordering of objects in a list but about sorting the object itself. Suppose the set weren't empty and I want to use sorted() to sort it:

class SetOfTwo(object):
    def __init__(self, a , b):
        el_0 = a
        el_1 = b

    def __len__(self):
        return 2

    def __str__(self):
        return '[{}, {}]'.format(el_0, el_1)

Is there a magic method I can implement to have sorted() flip the elements if they aren't in order? I'm picturing the following behavior:

>>> s = SetOfTwo(2, 1)
>>> str(s)
[2, 1]

>>> t = sorted(s)
>>> str(t)
[1, 2]

>>> type(t)
>>> SetOfTwo

解决方案

You should definitely read the official documentation of how to emulate container types. Basically a class supposed to work as a container (list, dict etc.) needs to implement methods to set or get members __getitem__(), __setitem__() and iterate over items __iter__() and to get the number of items - method __len__(). This is the minimum. But you can also add the ability to delete items and other operations.

The behaviour of sorted() built-in function is to iterate over elements of your container and compare them using methods you mentioned __cmp__(), __ge__(), __le__() which should be defined for items and not the container as you know already. Then a new list instance is created with items sorted and this new instance is returned. You can pass it to the constructor of your custom container then or you can wriap sorted() with a custom function which will return the desired class instance.

这篇关于Python 中有 sorted() 的神奇方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆