2016-03-03 97 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