鱼C论坛

 找回密码
 立即注册
查看: 1890|回复: 2

课后作业33讲最后一题

[复制链接]
发表于 2020-5-13 22:43:01 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
把文件关闭放在 finally 语句块中执行还是会出现问题,像下边这个代码,当前文件夹中并不存在"My_File.txt"这个文件,那么程序执行起来会发生什么事情呢?你有办法解决这个问题吗?>;
try:
    f = open('My_File.txt') # 当前文件夹中并不存在"My_File.txt"这个文件T_T
    print(f.read())
except OSError as reason:
    print('出错啦:' + str(reason))
finally:
    if 'f' in locals(): # 如果文件对象变量存在当前局部变量符号表的话,说明打开成功
        f.close()
答案这里的if ‘f’ in locals(),这个locals()是一个什么函数,有什么用  ,这里的‘f’ 是指代 f = open('My_File.txt') 这里的f在内存中占的内容吗,能举例详说一下locals()用法吗
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-5-13 22:53:14 | 显示全部楼层
locals() 如果在函数中调用则为局部变量字典,否则为全局变量字典
  1. >>> f
  2. Traceback (most recent call last):
  3.   File "<pyshell#19>", line 1, in <module>
  4.     f
  5. NameError: name 'f' is not defined
  6. >>> locals()['f']=0
  7. >>> f
  8. 0
复制代码
  1. >>> f=str()
  2. >>> locals()
  3. {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'f': ''}
  4. >>> del f #等价于 del locals()['f']
  5. >>> locals()
  6. {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}
复制代码
  1. >>> a=0
  2. >>> b=True
  3. >>> c=()
  4. >>> d='Hi'
  5. >>> a
  6. 0
  7. >>> b
  8. True
  9. >>> c
  10. ()
  11. >>> d
  12. 'Hi'
  13. >>> locals().clear()
  14. >>> a
  15. Traceback (most recent call last):
  16.   File "<pyshell#16>", line 1, in <module>
  17.     a
  18. NameError: name 'a' is not defined
  19. >>> b
  20. Traceback (most recent call last):
  21.   File "<pyshell#17>", line 1, in <module>
  22.     b
  23. NameError: name 'b' is not defined
  24. >>> c
  25. Traceback (most recent call last):
  26.   File "<pyshell#18>", line 1, in <module>
  27.     c
  28. NameError: name 'c' is not defined
  29. >>> d
  30. Traceback (most recent call last):
  31.   File "<pyshell#19>", line 1, in <module>
  32.     d
  33. NameError: name 'd' is not defined
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-5-13 23:00:15 | 显示全部楼层
楼上大佬的样子
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-30 04:55

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表