【发布时间】:2018-06-13 16:08:29
【问题描述】:
我有一个有两个属性(索引和值)的类。我希望能够调用 max 并只返回值(这是一个浮点数)。
p = [Point(1, 23.33), Point(2, 12.3)]
max(p)
#<Point object at 0x1052d4eb8>
# I would like to see 23.33
# float(max(p)) returns the float but I want to be able to use the max function by it self
我可以重写数据模型中的方法来强制max 只返回浮点数吗?下面是整个班级。
Python 3.6
class Point:
""" a set of data indexed by time """
def __init__(self, index, value):
self._index = index
self._value = value
def __float__(self):
return float(self._value)
def __add__(self, other):
return float(self._value) + other
def __radd__(self, other):
return self.__add__(other)
def __lt__(self, other):
return self._value < float(other)
def ___le__(self, other):
return self._value <= float(other)
def __eq__(self, other):
return self._value == float(other)
def __ne__(self, other):
return self._value != float(other)
def __gt__(self, other):
return self._value > float(other)
def __ge__(self, other):
return self._value >= float(other)
【问题讨论】:
-
这听起来真是个坏主意。只需致电
float。 -
你有方法覆盖吗?为什么不将强制执行的函数定义为成员函数,这样您就可以这样做:
p.max()? -
另外,
___le__有一个额外的_,您应该检查运算符重载中其他操作数的类型(并返回NotImplemented以获得不受支持的其他操作数)。 -
我很好奇。为什么你需要这种奇怪的行为?
-
max将提供您提供给它的最大对象,它不会进行自动转换 - 这不是它的工作。
标签: python python-3.x