2016-03-03 19 views
-3

所以我試圖實現一個點類,它創建一個點,然後旋轉,縮放和轉換點。這是我目前寫的。在Python中實現一個點類

class Point: 
    ''' 
     Create a Point instance from x and y. 
    ''' 
    def __init__(self, x, y): 
     self.x = 0 
     self.y = 0 

    ''' 
     Rotate counterclockwise, by a radians, about the origin. 
    ''' 
    def rotate(self, a): 
     self.x0 = math.cos(this.a) * self.x - math.sin(this.a) * self.y 
     self.y0 = math.sin(this.a) * self.x + math.cos(this.a) * self.y 

    ''' 

     Scale point by factor f, about the origin. 
    Exceptions 
     Raise Error if f is not of type float. 
    ''' 
    def scale(self, f): 
     self.x0 = f * self.x 
     self.y0 = f * self.y 

    ''' 
     Translate point by delta_x and delta_y. 
    Exceptions 
     Raise Error if delta_x, delta_y are not of type float. 
    ''' 
    def translate(self, delta_x, delta_y): 
     self.x0 = self.x + delta_x 
     self.y0 = self.y + delta_y 

    ''' 
     Round and convert to int in string form. 
    ''' 
    def __str__(self): 
     return int(round(self.x)) 

此代碼中的某些內容正在生成錯誤。現在我還沒有實現錯誤捕捉和我有在頂部

class Error(Exception): 
    def __init__(self, message): 
     self.message = message 

錯誤的方法,但我將如何捕捉錯誤,如果某個變量是float類型呢?

這裏的if語句我使用的一個:

def __init__(self, x, y): 
     if not isinstance(x, float): 
      raise Error ("Parameter \"x\" illegal.")   
      self.x = x 
      self.y = y 
     if not isinstance(y, float): 
      raise Error ("Parameter \"y\" illegal.") 
      self.x = x 
      self.y = y 

但是,這讓我的縮進錯誤。那麼,我怎樣才能打印出一個錯誤信息,說明哪個變量導致了問題?

+2

「的東西在這個代碼生成錯誤。 「什麼是產生錯誤? (提示:錯誤信息告訴你。) – kindall

+2

不應該'self.x = 0'是'self.x = x'而'self.y = 0'是'self.y = y'? – alecxe

+0

錯誤說 「 回溯(最近通話最後一個): 文件 」test_A.py「 17行,在 打印點(0.0,1.0) 類型錯誤:__str__返回非字符串(類型爲int) 」 –

回答

0

如果該變量不是浮點數,您將得到一個TypeError。你幾乎可以像這樣「捕捉」這些錯誤;

try: 
    pass # your stuff here. 
except e as TypeError: 
    print e # this means a type error has occurred, type is not correct. 

另外,這將是值得閱讀的檢查正確的類型在開始assert; https://wiki.python.org/moin/UsingAssertionsEffectively

1

如果你想提高一個例外,它做了點的初始化:

def __init__(self, x, y): 
    if not isinstance(x, float) or not isinstance(y, float): 
     raise Error("Point's coordinates must be floats.") 
    self.x = x 
    self.y = y 

或轉換座標浮動:

def __init__(self, x, y): 
    self.x = float(x) 
    self.y = float(y) 
+0

我在這裏使用了錯誤類,因爲你提到你有它的定義,但它可能應該更具體異常 – Karol

+0

應self.x = x和self.y = y在縮進內,因爲我不斷收到該行的錯誤。 –

+0

@DavidRolfe:self.x = x和self.y = Y應該是如果不... – Karol