简明Python教程学习笔记4

8、模块

(1)简介

  模块必须以.py作为文件的扩展名

(2)字节编译的.pyc文件

  .pyc文件与平台无关

(3)from...import语句

  一般说来,应该避免使用from..import而使用import语句,因为这样可以使你的程序更加易读,也可以避免名称的冲突。

(4)模块的__name__

1 # using_name.py
2 a_str = "This is a string"
3 if __name__ == '__main__':
4     print "This program is being run by itself"
5     print "Main:{0}".format(a_str)
6 else:
7     print "I am being imported from another module"
8     print "Import:{0}".format(a_str)
模块的__name__

输出:

1 # import_module.py
2 import using_name
3 
4 print "Use Import variable:{}".format(using_name.a_str)
import

输出:

  每个模块都有自己的__name__

(5)制造你自己的模块

  每个python程序就是一个模块,但要保证以.py作为扩展名

(6)dir()

dir函数来列出模块定义的标识符。标识符有函数、类和变量

 1 >>> __name__
 2 '__main__'
 3 >>> dir()
 4 ['__builtins__', '__doc__', '__name__', '__package__']
 5 >>> a = 5
 6 >>> dir()
 7 ['__builtins__', '__doc__', '__name__', '__package__', 'a']
 8 >>> del a
 9 >>> dir()
10 ['__builtins__', '__doc__', '__name__', '__package__']
11 >>> 
dir()

dir(),没有参数的时候,返回当前模块的属性列表

在当前模块添加变量或删除变量,都可以通过dir()来查看

1 >>> import sys
2 >>> dir(sys)
3 ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', '_mercurial', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_traceback', 'exc_type', 'exc_value', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'getwindowsversion', 'hexversion', 'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'py3kwarning', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions', 'winver']
4 >>> dir()
5 ['__builtins__', '__doc__', '__name__', '__package__', 'sys']
6 >>> 
dir(module)

dir(module)显示指定模块的标识符

 

转载于:https://www.cnblogs.com/xlsxiaolaoshu/p/8330807.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值