python的應該關注的語法

CL.TANG發表於2016-10-18

 

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 的裝飾器 @ 語法

想起裝飾器語法,就不由得想起有次面試,面試官問裝飾器的作用,當時很模糊,說的是

相關文章