posts - 431,  comments - 344,  trackbacks - 0
          從python2.1開始以后, 當一個新的語言特性首次出現在發行版中時候, 如果該新特性與以前舊版本python不兼容, 則該特性將會被默認禁用. 如果想啟用這個新特性, 則必須使用 "from __future__import *" 語句進行導入. 比如在2.5下使用with特性.

          from __future__ import with_statement

          with open('test.txt', 'r') as f:
              for line in f:
                  print line

          with方式語句可以替換以前try..catch語句, 如果使用try..catch語句則為:
          try:
              f = open('test.txt', 'r')
              for line in f:
                  print line
          finally:
              f.close()

          而with代碼塊如果內部出現任何錯誤, 都將會自動調用close方法

          如果上面的with代碼塊沒有使用from __future__ import with_statement, 代碼將會報錯, 提示你這個功能在2.6中實現.
          Warning: 'with' will become a reserved keyword in Python 2.6
          posted on 2009-05-27 13:33 周銳 閱讀(2740) 評論(0)  編輯  收藏 所屬分類: Python
          主站蜘蛛池模板: 扶绥县| 西贡区| 和田市| 开封县| 遂溪县| 西和县| 黑山县| 万安县| 泸定县| 茂名市| 德庆县| 瑞昌市| 济南市| 乌拉特前旗| 津市市| 南岸区| 枣庄市| 吉林市| 宁强县| 巧家县| 宿松县| 威宁| 峨眉山市| 天峻县| 林州市| 通辽市| 广水市| 苍南县| 达日县| 贵溪市| 旺苍县| 屯留县| 蓝山县| 楚雄市| 巩留县| 石景山区| 诏安县| 万州区| 天柱县| 博罗县| 蓬溪县|