Python 学习备忘 模块

1、模块是程序。

     任何python都可以作为模块导入,如果我们写了一个python程序,保存在f:/python/hello.py。

     hello.py如下:

     #hello.py

     print("hello,world");

2、如何导入该模块:

     import sys

     sys.path.append('f:/python')

     import hello

3、如果再次导入 import hello,就什么也没有了。

     因为导入模块并不意味着在导入时执行某些操作,主要用于定义,比如变量、函数和类等。因此应该导入一次,如果坚持重新载入模块,可以使用内建的reload函数。

4 、包涵函数的简单模块

      #hello2.py

      def hell0():

    print("hello, world")

  python shell代码:

    >>> import sys
    >>> sys.path.append('f:/python')
    >>> import hello2
    >>> hello2.hell0()

5、在模块中增加测试代码

  #hello3.py


  def hello():
    print("hello world test")

  #A test
    hello() # 测试代码

     测试代码在程序中是不希望执行 的,但是执行了,为了避免这种情况的关键在于:“告知” 模块本身是作为程序运行还是导入到其他程序。为了实现这一点,需要使用__name__变量:

    

     注:为了区分主履行文件还是被调用的文件,Python引入了一个变量__name__,当文件是被调用时,__name__的值为模块名,当文件被履行时,__name__为""__main__""。这个特点,为测试驱动开辟供给了极好的支撑,我们可以在每个模块中写上测试代码,这些测试代码仅当模块被Python直接履行时才会运行,代码和测试完美的连络在一路。

      python 代码:

#hello4.py
def hello():
print("hello world 4")

def test():
hello()

if __name__=='__main__':
test()

执行:

>>> import sys
>>> sys.path .append('f:/python')
>>> import hello4.py
>>> import hello4
>>> hello4.hello ()
hello world 4
>>> hello4.test()
hello world 4
>>>

原文地址:https://www.cnblogs.com/yhql/p/python.html