Is there a way to return a custom value for min and max in Python? -
i have custom class,
class a: def __init__(self, a, b): self.a = self.b = b
the class not iterable or indexable or that. if @ possible, keep way. possible have following work?
>>> x = a(1, 2) >>> min(x) 1 >>> max(x) 2
what got me thinking min
, max
listed "common sequence operations" in docs. since range
considered sequence type same docs, thinking there must sort of optimization possible range
, , perhaps take advantage of it.
perhaps there magic method not aware of enable this?
yes. when min
takes 1 arguments assumes iterable, iterates on , takes minimum value. so,
class a: def __init__(self, a, b): self.a = self.b = b def __iter__(self): yield self.a yield self.b
should work.
additional note: if don't want use __iter__
, don't know of way that. want create own min function, calls __min__
method if there 1 in argument passed , calls old min
else.
oldmin = min def min( *args ) if len(args) == 1 , hasattr( args[0], '__min__' ): return args[0].__min__() else: return oldmin( *args )
Comments
Post a Comment