所以我試圖實現一個點類,它創建一個點,然後旋轉,縮放和轉換點。這是我目前寫的。在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
但是,這讓我的縮進錯誤。那麼,我怎樣才能打印出一個錯誤信息,說明哪個變量導致了問題?
「的東西在這個代碼生成錯誤。 「什麼是產生錯誤? (提示:錯誤信息告訴你。) – kindall
不應該'self.x = 0'是'self.x = x'而'self.y = 0'是'self.y = y'? – alecxe
錯誤說 「 回溯(最近通話最後一個): 文件 」test_A.py「 17行,在 打印點(0.0,1.0) 類型錯誤:__str__返回非字符串(類型爲int) 」 –