1.try...finally

def test_return():
    try:
        print "try"
        raise ValueError("valueError")
    except:
        return "except"
    finally:
        print "finally"

print test_return()  

finally这种语法在很多语言都有的,并不是python的特殊语法,但还是提出来来说。

执行结果:

try
finally
except

去掉finally,代码为:

def test_return():
    try:
        print "try"
        raise ValueError("valueError")
    except:
        return "except"


print test_return()

执行结果:

try
except

这种应用主要体现在关闭数据库连接上最能体现:

        try:
            row = self._fetchone_impl()
        except Exception, e:
            self.connection._handle_dbapi_exception(
                                    e, None, None,
                                    self.cursor, self.context)
            raise

        try:
            if row is not None:
                return self.process_rows([row])[0]
            else:
                return None
        finally:
            self.close()

这是sqlAlchemy中截取的类似用法。

 

2.python 的装饰器 @ 语法

想起装饰器语法,就不由得想起有次面试,面试官问装饰器的作用,当时很模糊,说的是

相关文章:

  • 2021-07-15
  • 2021-05-05
  • 2022-12-23
  • 2021-08-22
  • 2021-10-19
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-08-11
  • 2021-05-06
  • 2022-01-06
  • 2021-12-12
  • 2022-01-25
  • 2021-05-25
相关资源
相似解决方案