Why can’t you define “round” for non-swimmers?

Given a simple class like

class Vector(object): def __init__(self, value): self.value = value def __abs__(self): return math.sqrt(sum([x**2 for x in self.value])) def __round__(self, *n): return [round(x,*n) for x in self.value] 

why abs(Vector([-3,4])) correctly gives 5 , and round(Vector([-3.1,4])) complains about TypeError: a float is required instead of the desired [-3,4] and how can this be to fix?

I know that round should usually return a float, but for a vector, as in this example, there is probably no ambiguity in the possible value, so why can't this just be overridden? Do I really need to subclass numbers.Real or define Vector(...).round(n) instead?

+2
python class rounding
Apr 17 '13 at 11:14
source share
1 answer

The __round__ special method was introduced only in Python 3. There is no special method support in Python 2.

You will need to use the highlighted method instead of the function:

 class Vector(object): def __init__(self, value): self.value = value def round(self, n): return [round(x, n) for x in self.value] 

or you will need to provide your own round() function:

 import __builtin__ def round(number, digits=0): try: return number.__round__(digits) except AttributeError: return __builtin__.round(number, digits) 

You can even defuse this in the __builtins__ namespace:

 import __builtin__ _bltin_round = __builtin__.round def round(number, digits=0): try: hook = number.__round__ except AttributeError: return _bltin_round(number, digits) else: # Call hook outside the exception handler so an AttributeError # thrown by its implementation is not masked return hook(digits) __builtin__.round = round 
+6
Apr 17 '13 at 11:18
source share



All Articles