如何在Python中多次返回对象?

时间:2019-03-25 06:57:36

标签: python

在Python类中执行异常处理时遇到问题。 我的课程结构是:

class base():
    def func():
        try:
            # some codes to deal with requests headers in here
            requests.get('...', timeout=0.1)
            return something
        except:
            # So when timeout in request occurs, func() will return 'Error'
            return 'Error'

    def A():
        func()

    def B():
        func()
    # there are about 10 functions that have called func().

    def index():
        reply = A()
        reply = B()
        # and A() B() functions are called here.
        return reply

我的问题是,是否有一种方法可以直接返回'Error'到索引函数,而不是每次调用时都进行异常处理?也就是说,仅更改func(),它必须返回2次(func()-> A()-> index()),因此索引函数中的reply将是'Error'。 / p>

3 个答案:

答案 0 :(得分:0)

您可以尝试以下操作:

def func():
  try:
     # the area may raise excetion
     pass
  except Exception1:
     # anything you like
     return 'error'
  except Exception2:
     # anything you like
     return 'error'

答案 1 :(得分:0)

def test(a = 1):
  try:
     if a:
         raise Exception
     else:
         return a+10
  except:
     return "error"

答案 2 :(得分:0)

使用requests.Timeout

def func():
    try:
        # some codes to deal with requests headers in here
        rq = requests.get('...', timeout=0.1)
        return 'something'
    except requests.Timeout as err:
        # So when timeout in request occurs, func() will return 'Error'
        return ('Error {}'.format(err))