Subclassing the min() build-in function?
Eddie Corns
eddie at holyrood.ed.ac.uk
Wed Nov 6 13:00:26 EST 2002
oracle_vs_ms at yahoo.dk (Peter Lorenzen) writes:
>Hi,
>I am using Jython to calculate a string like this: "2+3+min(1,2,3)"
>from my Java pro-gram. This works beautifully. But my problem is that
>if a user wants to calculate min(1) Python considers this an error. I
>want it to return 1. If I could figure out how to subclass the min
>function, so when it was called with one parameter I just returned
>this parame-ter, and otherwise returned the super min function. It
>looks like this should be possible, but I am new to Python, so I don't
>understand the subclass examples I have found.
Something like:
def min(*a):
if len(a) == 1: return a[0]
return __builtins__.min (*a)
Example:
>>> def min(*a):
... if len(a) == 1: return a[0]
... return __builtins__.min (*a)
...
>>> min(2)
2
>>> min(1,2)
1
>>> min(3,2,1)
1
>>> min([1,2,3])
[1, 2, 3]
The last example shows that you might want to check whether 'a' is a sequence
if that's ever likely to happen. Using __builtins__.min is easier than making
a local copy of the standard min which could have been done by:
real_min = min
def min(*a):
if len(a) == 1: return a[0]
return real_min (*a)
This is not subclassing, min is a function not a class so it's just redefining
the function - this may explain why you were going astray (in Python not
everything is an object thankfully).
Eddie
More information about the Python-list
mailing list