使用模块
1. import module
使用时modulename类似namespace
2. from module import 函数和变量列表
类似using namespace的功效,不推荐。
3. import module as anothername
很面熟的语法,忘记哪儿见过。给导入模块起别名。
被调用模块
#!/usr/bin/python
# Filename: mymodule.py
import sys
def sayhi():
if __name__ == '__main__':
print 'Hi, this is mymodule speaking, called by myself.'
else :
print 'Hi, this is mymodule speaking, called by another.'
dir()
# Filename: mymodule.py
import sys
def sayhi():
if __name__ == '__main__':
print 'Hi, this is mymodule speaking, called by myself.'
else :
print 'Hi, this is mymodule speaking, called by another.'
dir()
version = '0.1'
调用者模块
#!/usr/bin/python
# Filename: mumodule.py
import mymodule
mymodule.sayhi()
print 'Version',mymodule.version
# Filename: mumodule.py
import mymodule
mymodule.sayhi()
print 'Version',mymodule.version
入口模块__main__
如题的意思。__name__的值要么是模块名,要么是__main__
一个有用的函数dir(modulename)
返回该模块使用的模块、函数、变量的列表。
无参数是返回当前模块的blablabla...
唉。。一种电击疗法也没办法治愈的暴戾焦虑烦躁