精确引入模块中的函数:
from math import sqrt
这样可以精确的引入math模块中的sqrt函数,但是并不建议使用这样的方法。原因是当两个模块含有同名函数时,这样的做法会引起一些问题(后来引入的函数会覆盖掉先前引入的同名函数)。
一个自定义的模块如下:
def to_celsius(t):
return (t - 32.0) * 5.0 / 9.0
def above_freezing(t):
return t > 0
这里的第二个above_freezing函数:
当其参数值大于冰点时(摄氏温度)返回True,否则返回False. 这里写得相当简洁,值得学习。
一个测试:
# experiment.py
print "The panda's scientific name is 'Ailuropoda melanoleuca'"
执行结果如下:
>>> import experiment
The panda's scientific name is 'Ailuropoda melanoleuca'
>>> import experiment
>>>
Python在首次引入模块的同时就会将其执行一次,并将其加载到内存,第二次加载相同模块时被无视。
文档字符串(docstring)- 提供帮助信息:
'''Function for working with temperature.'''
def to_celsius(t):
'''Convert Fahrenheit to Celsius.'''
return (t - 32.0) * 5.0 / 9.0
def above_freezing(t):
'''True if temperature in Celsius is above freezing, False otherwise.'''
return t > 0
执行结果:
>>>import notes
Help on module notes:
NAME
notes - Function for working with temperature.
FILE
c:\users\peterwin7\desktop\practicalprogramming\notes.py
FUNCTIONS
above_freezing(t)
True if temperature in Celsius is above freezing, False otherwise.
to_celsius(t)
Convert Fahrenheit to Celsius.
使用__main__
所有Python文件既可以直接在命令行中执行,也可以再IDE中执行,还可以由别的程序来使用。
为了便于了解这个状况,Python在每个模块中都定义了一个叫做__name__的特殊变量:
if __name__ == "__main__":
print "I am the main program"
else:
print "Someone is importing me"
当Python引入一个模块时,就是将该模块的__name__变量设置为它的名称,而不是特殊字符串“__main__”,
也就是说,模块能够明白自己是否是主程序。