python的应该关注的语法

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 的装饰器 @ 语法

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

原文地址:https://www.cnblogs.com/CLTANG/p/2708689.html