2013-04-17 40 views
2

鑑於像爲什麼不能爲非浮游物定義「round」?

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] 

一個簡單的類爲什麼abs(Vector([-3,4]))正確產生5round(Vector([-3.1,4]))TypeError: a float is required,而不是期望[-3,4]抱怨,以及如何這個問題能解決?

我知道round通常應該返回一個浮點數,但對於這個例子中的向量,可能的含義可能沒有模棱兩可的含義,那麼爲什麼不能簡單地重寫呢?我真的必須繼承numbers.Real,還是定義Vector(...).round(n)

回答

6

__round__特殊方法在Python 3只介紹在Python的特殊方法不支持2

你必須使用專用的方法,而不是功能:

class Vector(object): 
    def __init__(self, value): 
     self.value = value 

    def round(self, n): 
     return [round(x, n) for x in self.value] 

或者你必須提供自己的round()功能:

import __builtin__ 

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

你甚至猴子補丁到這個命名空間:

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 
+0

我明白了,在這種情況下,我應該標記的問題[標籤:蟒蛇-2.7],以及...做同樣適用於'math.floor'等人?是否沒有'__future__ import'來解決這個問題? –

+0

不,不幸的是,沒有'__future__'開關會啓用該行爲。 –

+0

無賴:-(這是一個非常有說服力的論據,以切換到我的Python 3然後... –

相關問題