Modules

module_using_sys.py

# 通过函数我们可以重用代码
# 通过模块Modules我们可以重用函数

# 编写模块 一种方法是编写一个.py后缀的文件
# 还有就是使用编写Python解释器的本地语言来编写模块 
# 比如  使用C语言来撰写Python模块


# 标准库模块
import sys


print('The command line arguments are:')
for item in sys.argv:
    print(item)

print('The PYTHONPATH is', sys.path,'\n')

module.using_name.py

# 为了降低导入模块的代价
# Python创建按照字节码编译的文件,后缀名为.pyc
# 字节码编译的文件是独立于运行平台的

#尽量使用improt 而不是 from...import

from math import sqrt
print('Square root of 16 is', sqrt(16))



# 模块的名字可以确定它是独立运行的还是被导入进来运行的
# 通过模块的__name__属性来实现

if __name__ == '__main__':
    print('This program is being run by itself')
else:
    print('I am being imported from another module')

mymodule.py

def say_hi():
    print('Hi, this is mymodule speaking.')

__version__ = '0.1'

mymodule_demo.py

#这里要保证两个module在同一目录下或者将mymodule导入到environment path里
import mymodule

mymodule.say_hi()
print('Version', mymodule.__version__)

mymodule_demo2.py

from mymodule import say_hi,__version__

say_hi()
print('Version', __version__)

# 还可以使用 from mymodule import *
# 它可以导入say_hi等所有公共名称,但不会导入__version__这种双下划线开头的
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容