Python基础教程系列四:函数与模块二

2019-09-25  本文已影响0人  奇遇Python

今天教程大纲如下所示主讲:闭包 修饰符 模块


image.png

闭包

什么是闭包?
如果在一个函数的内部定义了另一个函数,外部的函数叫它外函数,内部的函数叫它内函数。
形成闭包的条件
1、必须要有一个内嵌函数
2、内嵌函数中要对自由变量的引用
3、外部函数必须返回内嵌函数

# python 中的闭包
def a():
    print("hello a")
    def b():
        print("hello b")
    return b
f1 = a()
f1()
# 打印结果为 hello a hello b

修饰器(装饰器)

修饰器可以理解为:是修改其他函数的功能的函数。
修饰器的作用:修饰器可以避免许多重复的动作。用@+修饰函数放在待修饰的函数头上就可以实现优化函数的功能

def use_logging(func):
  print("%s is running" % func.__name__) 
  return func
@use_logging
def bar():
  print('i am bar')
bar()
#输出结果为:
# bar is running
# i am bar

模块

1、Anaconda是一个用于科学计算的 Python 发行版,支持 Linux, Mac, Windows, 包含了众多流行的科学计算、数据分析的 Python 包。
2、pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pyspider,这样就会从清华这边的镜像去安装pyspider库(其他地址同理)。
阿里云:http://mirrors.aliyun.com/pypi/simple/
豆瓣:http://pypi.douban.com/simple/
清华:https://pypi.tuna.tsinghua.edu.cn/simple

#!/usr/bin/python
# -*- coding: utf-8 -*-
#需要先  pip3 install requests (用来安装第三方的演示)

import sys  # 这里调用的是内置模块
from hello import *  # 导入自定义hello.py内的所有函数
import requests #让http服务人类

def printSys():
    print(sys.path)  # sys.path 是python的搜索模块的路径集,是一个list

def testHelllo():
    hello() #这里将会调用在hello.py 文件中的 hello 函数 此时会打印hello Python

def requestResult():
    response = requests.get("http://www.baidu.com/")
    print(response.url)

if __name__ == '__main__':
    testHelllo()
    printSys()
    requestResult()
上一篇 下一篇

猜你喜欢

热点阅读