在python中打印出错误消息

时间:2016-03-07 19:50:02

标签: python

所以对于一个点类我会让我有这个错误类:

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

我使用它来引发错误并打印出某些错误的消息。如果x或y(或两者)都不是浮点值,我在这里做的就是打印出错误信息:

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

通过这种方式引发和打印错误,我得到的错误信息如下:

********** Point
*** constructor
caught: Parameter "x" illegal.
caught: Parameter "y" illegal.
0
***

但错误信息实际上应该是这样的:

********** Point
*** constructor
caught: Parameter "x" illegal.
caught: Parameter "y" illegal.
0 1
***

那么为什么期望的输出在0旁边打印1?其他错误消息还包括:

*** rotate
caught: Parameter "a" illegal.
0
***

当我希望它看起来像:

*** rotate
caught: Parameter "a" illegal.
0 -1
***

那么我的错误消息中是否有我没有打印出来的东西?这是打印出错误消息的代码:

print '*** constructor'
try:
    p0 = Point(1,1.0) # x illegal
except Error as e:
    print 'caught:', e.message
try:
    p0 = Point(1.0,'y') # y illegal
except Error as e:
    print 'caught:', e.message

print Point(0.0,1.0)

这是 str 方法:

def __str__(self):
    return str(int(round(self.x)))

2 个答案:

答案 0 :(得分:0)

默认x和y为无:

x = None
y = None

然后在str方法中,

def __str__(self):
    str_x = ""
    if self.x is not None:
        str_x = str(int(round(self.x)))
    str_y = ""
    if self.y is not None:
        str_y = str(int(round(self.y)))
    return "%s %s" % (str_x, str_y)

答案 1 :(得分:0)

为什么不使用python的内置加注?

它将终止程序并显示错误消息,就像它从解释器中出来一样。

如果您对该课程挑剔,请按以下方式定义:

raise ExampleError("Parameter \"x\" illegal.","Parameter \"y\" illegal.")

无论你是否定义了这个类,都要这样举起来:

Traceback (most recent call last):
  File "C:/testanswer.py", line 3, in <module>
    raise ExampleError("Parameter \"x\" illegal.","Parameter \"y\" illegal.")
ExampleError: ('Parameter "x" illegal.', 'Parameter "y" illegal.')

它将显示以下输出:

package com.github.jreddit.oauth does not exist

对于单个答案,没有必要将其置于元组中。