2
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]))
正確產生5
而round(Vector([-3.1,4]))
與TypeError: a float is required
,而不是期望[-3,4]
抱怨,以及如何這個問題能解決?
我知道round
通常應該返回一個浮點數,但對於這個例子中的向量,可能的含義可能沒有模棱兩可的含義,那麼爲什麼不能簡單地重寫呢?我真的必須繼承numbers.Real
,還是定義Vector(...).round(n)
?
我明白了,在這種情況下,我應該標記的問題[標籤:蟒蛇-2.7],以及...做同樣適用於'math.floor'等人?是否沒有'__future__ import'來解決這個問題? –
不,不幸的是,沒有'__future__'開關會啓用該行爲。 –
無賴:-(這是一個非常有說服力的論據,以切換到我的Python 3然後... –