相关疑难解决方法(0)

什么是python"with"语句专为什么设计的?

with今天第一次遇到了Python 语句.我已经使用Python几个月了,甚至不知道它的存在!鉴于其地位有点模糊,我认为值得问:

  1. 什么是with设计用于的Python 语句?
  2. 你用它来做什么?
  3. 是否有任何我需要注意的问题,或与其使用相关的常见反模式?任何try..finally比它更好用的情况with
  4. 为什么它的使用范围更广?
  5. 哪些标准库类与它兼容?

python language-features with-statement

396
推荐指数
7
解决办法
9万
查看次数

解释Python的'__enter __'和'__exit__'

我在某人的代码中看到了这个.这是什么意思?

    def __enter__(self):
        return self

    def __exit__(self, type, value, tb):
        self.stream.close()
Run Code Online (Sandbox Code Playgroud)
from __future__ import with_statement#for python2.5 

class a(object):
    def __enter__(self):
        print 'sss'
        return 'sss111'
    def __exit__(self ,type, value, traceback):
        print 'ok'
        return False

with a() as s:
    print s


print s
Run Code Online (Sandbox Code Playgroud)

python oop with-statement

314
推荐指数
6
解决办法
21万
查看次数

标签 统计

python ×2

with-statement ×2

language-features ×1

oop ×1