有没有办法在 Python 中返回 min 和 max 的自定义值? [英] Is there a way to return a custom value for min and max in Python?

查看:46
本文介绍了有没有办法在 Python 中返回 min 和 max 的自定义值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义类,

A 类:def __init__(self, a, b):self.a = a自我.b = b

该类不可迭代或不可索引或类似的东西.如果可能的话,我想保持这种状态.是否有可能有类似以下的工作?

<预><代码>>>>x = A(1, 2)>>>分钟(x)1>>>最大值(x)2

让我想到这一点的是 minmax 已列出作为 docs 中的通用序列操作".由于 range 被认为是一个序列键入完全相同的文档,我认为必须对 range 进行某种优化,也许我可以利用它.

也许有一种我不知道的神奇方法可以实现这一点?

解决方案

是的.当 min 接受一个参数时,它假定它是一个可迭代的,迭代它并取最小值.所以,

A 类:def __init__(self, a, b):self.a = a自我.b = bdef __iter__(self):屈服自我.a屈服自我.b

应该可以.

附加说明:如果您不想使用 __iter__,我不知道怎么做.您可能想要创建自己的 min 函数,如果传递给它的参数中有一个方法,则调用一些 _min_ 方法,并调用旧的 min 其他方法.

oldmin = min定义分钟(*参数):如果 len(args) == 1 和 hasattr(args[0], '_min_'):返回 args[0]._min_()别的:返回 oldmin(*args)

I have a custom class,

class A:
    def __init__(self, a, b):
        self.a = a
        self.b = b

The class is not iterable or indexable or anything like that. If at all possible, I would like to keep it that way. Is it possible to have something like the following work?

>>> x = A(1, 2)
>>> min(x)
1
>>> max(x)
2

What got me thinking about this is that min and max are listed as "Common Sequence Operations" in the docs. Since range is considered to be a sequence type by the very same docs, I was thinking that there must be some sort of optimization that is possible for range, and that perhaps I could take advantage of it.

Perhaps there is a magic method that I am not aware of that would enable this?

解决方案

Yes. When min takes one arguments it assumes it to be an iterable, iterates over it and takes the minimum value. So,

class A:
    def __init__(self, a, b):
        self.a = a
        self.b = b
    def __iter__(self):
        yield self.a
        yield self.b

Should work.

Additional Note: If you don't want to use __iter__, I don't know of way to do that. You probably want to create your own min function, that calls some _min_ method if there is one in the argument it is passed to and calls the old min else.

oldmin = min
def min(*args):
    if len(args) == 1 and hasattr(args[0], '_min_'):
        return args[0]._min_()
    else:
        return oldmin(*args)

这篇关于有没有办法在 Python 中返回 min 和 max 的自定义值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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