python学习之旅(十六)

Python基础知识(15):模块

1、可以把模块想象成导入Python以增强其功能的扩展

2、任何程序都可以作为模块导入

3、导入模块并不意味着在导入的时候执行某些操作,它们主要用于定义变量、函数和类等

#hello1.py
def hello():
    print("Hello,world!")

hello()

  >>> import hello1
  Hello,world!

  >>> hello1.hello()
  Hello,world!

4、为了方便代码重用,把程序模块化

5、有些模块被导入时会运行,为了避免这种情况,使用'__name__'变量,“告知”模块本身作为程序运行还是导入

 注:name前面和后面为两个下划线

>>> __name__
'__main__'

>>> hello1.__name__
'hello1'

在“主程序”中,变量'_name_'的值是'_main_',而在导入的模块中,这个值就被设定为模块的名字

为了让模块测试代码更好用,可以将其置在if语句中

#hello2.py
def hello():
    print("Hello,world!")

def test():
    hello()

if __name__=="__main__":
    test()

>>> import hello2 >>> hello2.hello() Hello,world!

6、模块的作用域

一般情况下,函数和变量是公开的(public)。如果我们想要某个函数或变量只在这个模块中使用,需要在函数名或变量名前面加前缀'__',表示这个函数或变量是私有的(private)

#hello3.py
def __hello_1(name):
    return "Hello,%s!"%name

def __hello_2(name):
    return "Hey,%s,your angle."%name

def greeting(name):
    if len(name)>4:
        return __hello_1(name)
    else:
        return __hello_2(name)


import hello3
>>> hello3.greeting("Alice")
'Hello,Alice!'
>>> hello3.greeting("Jack")
'Hey,Jack,your angle.'

7、安装第三方模块

在windows系统下安装Python的第三方库,以便导入某些模块

根据自己安装的Python版本选择相应的包管理工具pip或Anaconda进行安装

原文地址:https://www.cnblogs.com/finsomway/p/10025755.html