Python 3.x 自定义异常打印每个参数字母的内容是什么?

Python 3.x 自定义异常打印每个参数字母的内容是什么?,python-3.x,Python 3.x,在Python 3中,我可以将一个参数传递到一个异常中,并以相同的方式打印出来: try: raise Exception('my exception') except Exception as ex: print(ex.args) (‘我的例外’,) 如果我定义一个自定义异常,它会将每个字母打印为参数。我做错了什么 class Networkerror(RuntimeError): def __init__(self, arg): self.args = a

在Python 3中,我可以将一个参数传递到一个异常中,并以相同的方式打印出来:

try:
    raise Exception('my exception')
except Exception as ex:
    print(ex.args)
(‘我的例外’,)

如果我定义一个自定义异常,它会将每个字母打印为参数。我做错了什么

class Networkerror(RuntimeError):
   def __init__(self, arg):
      self.args = arg

try:
   raise Networkerror('Bad hostname')
except Networkerror as e:
   print(e.args)
(‘B’、‘a’、‘d’、‘h’、‘o’、‘s’、‘t’、‘n’、‘a’、‘m’、‘e’)

,但您为其指定了一个普通的
str
。这恰好起作用,因为
str
s是其字符的组合;打开包装进行打印时,它们看起来与单个字母的元组相同。您可以在单个元素
元组中换行以修复:

class Networkerror(RuntimeError):
   def __init__(self, arg):
      self.args = arg,
或者接受隐式生成
元组的位置变量:

class Networkerror(RuntimeError):
   def __init__(self, *args):
      self.args = args
或者不在子类上定义
\uuuuu init\uuuu
,让基类正常处理它(当您没有需要自己处理的特殊参数时,通常是正确的解决方案):

,但您为其指定了一个普通的
str
。这恰好起作用,因为
str
s是其字符的组合;打开包装进行打印时,它们看起来与单个字母的元组相同。您可以在单个元素
元组中换行以修复:

class Networkerror(RuntimeError):
   def __init__(self, arg):
      self.args = arg,
或者接受隐式生成
元组的位置变量:

class Networkerror(RuntimeError):
   def __init__(self, *args):
      self.args = args
或者不在子类上定义
\uuuuu init\uuuu
,让基类正常处理它(当您没有需要自己处理的特殊参数时,通常是正确的解决方案):