with 语句是从 Python 2.5 开始引入的一种与异常处理相关的功能(2.5 版本中要通过 from __future__ import with_statement 导入后才可以使用),从 2.6 版本开始缺省可用(参考 What's new in Python 2.6"color: #ff0000">术语
要使用 with 语句,首先要明白上下文管理器这一概念。有了上下文管理器,with 语句才能工作。
在python中读写操作资源,最后需要释放资源。可以使用try…finally结构实现资源的正确释放,python提供了一个with语句能更简便的实现释放资源。
1. python像文件的操作open等已经可以直接使用with语句
2. 可以自定义一个支持with语句对象
3. 使用contextlib也可以使用with语句对象
4. 针对需要close操作的对象with的使用
示例代码中有4种使用标注
# 自定义支持with语句的对象 class DummyRes: def __init__(self, tag): self.tag = tag def __enter__(self): print("Enter > {}".format(self.tag)) return self def __exit__(self, exc_type, exc_value, exc_tb): print("Exit <<< {}".format(self.tag)) if exc_tb is None: print("Exit without Exception {}".format(self.tag)) return False else: print("Exit with Exception {}".format(self.tag)) return True # 支持closing 上下文with语句对象 class Closing: def __init__(self, thing): self.thing = thing def __enter__(self): return self def __exit__(self, exc_type, exc_value, exc_tb): self.thing.close() class ClosingDemo: def __init__(self): self.acquire() def acquire(self): print("Acquire RES") def close(self): print("Close RES") from contextlib import contextmanager class ContextDemo: def __init__(self): print("Context Demo init") raise Exception print("Context Demo init") def print(self): print("Context Demo print 1") #raise Exception print("Context Demo print 2") def close(self): print("Context Demo close") def context_demo(): print("context demo in") raise Exception print("context demo out") @contextmanager def demo(): print("Allocate Resoures") try: yield context_demo finally: print("raise exception") #yield "*** contextmanager demo ***" print("Free Resoures") if __name__ == "__main__": # 1. 使用with语句 (自动关闭文件) with open("test.txt", "w") as f: f.write("write test") # 2. 自动定义with语句 with DummyRes("test") as res: print("With body 1") raise Exception print("With body 2") # 3. 利用contextlib定义with语句 with demo(): print("exc demo") # 4. closing 上下文 (适合有close操作的情况) with Closing(ClosingDemo()): print("Use Resoures")
总结
以上所述是小编给大家介绍的python with语句简介,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!
python,with语句
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线
暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。
艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。
《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。