学习python_day4

目录:

  •    闭包函数
  •    装饰器
  •    模块与

一、函数是第一类对象

  定义一个函数相当于定义一个变量一样,例如:

func = "函数里的内容"

def func():--->相当于变量的名 func

  print("in the func") --->相当于变量的内容“函数的内容

func() 函数的特别之处就是可以被调用的,func找到函数加()是运行,运行后先检查函数里的语法是否正确,正确则执行

所以变量有啥特性,函数也就有啥特性,例如:变量可赋值 那么函数就也可以 func = f1 运行时f1()就等同于func()

当做参数使用

def fool(a):

  a()

fool(func)

返回值可以是函数

def fool2():

  return func

res=fool2()

res()---->func()

可以作为容器的元素

fool3= {"func":func}

fool3["func"]()就是在调用func()函数

so 函数是第一类对象的意思就是函数可以被当做数据来传递

二、函数的嵌套

嵌套的调用

def my_max(x,y):
    if x>y:
        return x
    else:
        return y
def my_max4(a,b,c,d):
    res1=my_max(a,b)
    res2=my_max(res1,c)
    res3=my_max(res2,d)
    return res3
print(my_max4(3,8,9,10))

嵌套的定义

x=1
def f1():
    def f2(): #相当于定义变量名f2
        print(x) #相当于变量的内容
    return f2 #返回变量f2
func=f1() #运行f1()就是在执行 定义变量f2和返回f2 并赋值给func相当于func=f2
func() #运行func()就等同于运行f2()

三、闭包函数
内部函数有对外部函数名字的引用,而不是全局的变量引用,因此这个内部函数就被称之为闭包函数

def f1(): #外部函数
    x = 10
    def f2():#内部函数  这样的函数也被称之为闭包函数
        print(x) #对外部函数的x变量的引用
    return f2
f=f1() # 这一步是把变量 x 和函数f2打包到f中了,就是隐藏了变量x=10,但这步并没有执行f2函数
f() #这步是在运行f2()函数,也可以不执行此不,以后想什么时候执行都行,直接调用f(),这就是他的延时性。
当执行f1()时会把参数10传递进来,相当于在函数f1中定义了一个变量x=10,这样内部函数f2也可以引用到,这样的内部函数也是闭包函数

def f1(x):
会执行定义一个变量 x=10
  
def f2():
print(x) f2会调用传进到f1中的参数x
return f2
f = f1(10)
f()

 四、装饰器

1、什么是装饰器

器即函数

装饰即修饰,意指为其他函数添加新功能

装饰器定义:本质就是函数,功能就是为其他函数添加新功能

2、装饰器遵循的原则

不修改被修饰函数的源代码(开放封闭原则)

为被修饰函数添加新功能,不修改被修饰函数的调用方式

3.实现装饰器的所需要哪些知识

装饰器=高阶函数+嵌套函数+闭包函数

4.回顾下高阶函数

高阶函数定义:

  1. 函数接受的参数是一个函数
  2. 函数的返回值是一个函数名
  3. 满足以上任意条件都可称之为高阶函数

5.装饰器的语法

 1 @timer #这步相当于 index= timer(index)
 2 def index():#  当一个函数在被定义时只要它的上方出现@加一个名字就会执行index=timer(index)
 3     print("in the index")
 4 index()#这样函数在执行时index其实是被timer处理过的
 5 
 6 #当出现多个装饰器时,按从下到上的顺序执行
 7 @timer3
 8 @timer2
 9 @timer1#--->func=timer1(index)--->func2=timer2(func)--index=timer3(func2)-->index=timer3(timer2(timer1(index)))
10 def index():#  当一个函数在被定义时只要它的上方出现@加一个名字就会依次执行上述所述的内容
11     print("in the index")
12 index()#这样函数在执行时index其实是被最后的timer3处理过的

6.无参装饰器示例

示例1:计算一个函数的运行时间

import time #导入时间函数包
def timer(func):#传递进来的参数func就等同于index,并执行了定义变量func=index
    def wrapper():
        start_time = time.time()#计算当前时间赋值给变量start_time
        func()#运行函数,就是在运行index(),因为此时的func就是index
        stop_time = time.time()#计算现在的时间
        print("index run time is %s"%(start_time-stop_time))#打印时间差
    return wrapper#返回wrapper
@timer#执行的操作index=timer(index) 此时index就是装饰器处理后返回的值,即index=wrapper
def index():
    print("in the index")
index()#执行函数就是在运行wrapper()函数,此时的index就是wrapper

示例2:当函数出现参数和返回值时

import time
def timer(func):
    def wrapper(msg):
        strat_time = time.time()
        func(msg)
        stop_time=time.time()
        print("index run time is %s"%(stop_time-strat_time))
    return wrapper
@timer
def index(msg):
    print("in the index %s"%msg)
index("hello world!")
import time
def timer(func):
    def wrapper(*args,**kwargs):#(tom,age=30)-->(tom){age:30},所以函数中无论传什么参数都可以用*args,**kwargs代替
        strat_time = time.time()
        res=func(*args,kwargs)#home(tom,age=30)-->home(name,age) res就是运行完被装饰函数的结果
        stop_time=time.time()
        print("index run time is %s"%(stop_time-strat_time))
        return res #返回被装饰函数的执行结果如home函数中是执行后返回beautiful,这里就等同于返回beautiful
    return wrapper
def index(msg):
    print("in the index %s"%msg)
index("hello world!")#等同于运行wrapper函数
@timer
def home(name,age):
    print("in the home %s %s"%(name,age))
    return "beautiful"
reslut=home("tom",age=30) #-->reslut=wrapper("tom",age=30)就是wrapper函数的返回值
print(reslut)

7.有参装饰器语法

def timer():
    pass
@timer(msg="hello world")#当装饰器有参数时,先执行timer函数得到一个结果res,此时相当于@res,然后执行index=res(index)
def index():              #装饰器其实也是函数,跟上()就后执行,执行完后返回结果
    print("in the index")
index()

示例1当用户认证通过后才执行函数

def auth_deco(func):
    def wrapper(*args,**kwargs):
        username=input("username:")
        passwd =input("password:")
        if username == "alex"and passwd =="alex3714":
            return func(*args,**kwargs)
    return wrapper
@auth_deco
def index(msg):
    print("in the index")
index("hello")

示例2对上个示例做进一步扩展,当出现不同的认证方式时

 1 def auth(fx):#执行时会定义auth_deco函数,并定义变量fx=file
 2     def auth_deco(func):#此时auth_deco函数就是个闭包函数,也就能接收到auth传进来的参数file
 3         def wrapper(*args, **kwargs):#同样wrapper也能引用到上层函数auth_deco传进来的变量func=index fx=file,就可以判断了
 4             username = input("username:")
 5             passwd = input("password:")
 6             if fx == "file":
 7                 if username == "alex" and passwd == "alex3714":
 8                     return func(*args, **kwargs)
 9             elif fx =="ldap":
10                 print("----->ldap")
11                 return func(*args,**kwargs)
12             else:
13                 print("other")
14         return wrapper
15     return auth_deco
16 @auth("file")#运行auth("file")-->auth_deco-->@auth_deco-->index=auth_deco(index)
17 def index(msg):
18     print("in the index")
19 index("hello")
20 @auth("ldap")
21 def home(page):
22     print("in the home")
23 home("qqq")

示例3再进一步更改使其一个函数验证通过其他函数不用验证

user_list=[
    {'name':'alex','passwd':'123'},
    {'name':'linhaifeng','passwd':'123'},
    {'name':'wupeiqi','passwd':'123'},
    {'name':'yuanhao','passwd':'123'},
]

current_user={'username':None,'login':False}
def auth(auth_type='file'):
    def auth_deco(func):
        def wrapper(*args,**kwargs):
            if auth_type == 'file':
                if current_user['username'] and current_user['login']:
                    res=func(*args,**kwargs)
                    return res
                username=input('用户名: ').strip()
                passwd=input('密码: ').strip()

                for index,user_dic in enumerate(user_list):
                    if username == user_dic['name'] and passwd == user_dic['passwd']:
                        current_user['username']=username
                        current_user['login']=True
                        res=func(*args,**kwargs)
                        return res
                        break
                else:
                    print('用户名或者密码错误,重新登录')
            elif auth_type == 'ldap':
                print('巴拉巴拉小魔仙')
                res=func(*args,**kwargs)
                return res
        return wrapper
    return auth_deco


#auth(auth_type='file')就是在运行一个函数,然后返回auth_deco,所以@auth(auth_type='file')
#就相当于@auth_deco,只不过现在,我们的auth_deco作为一个闭包的应用,外层的包auth给它留了一个auth_type='file'参数
@auth(auth_type='ldap')
def index():
    print('欢迎来到主页面')

@auth(auth_type='ldap')
def home():
    print('这里是你家')

def shopping_car():
    print('查看购物车啊亲')

def order():
    print('查看订单啊亲')

# print(user_list)
index()
# print(user_list)
home()

带参装饰器
View Code

8、模块

(1)什么是模块?

一个模块就是一个包含了python定义和声明的文件,文件名就是模块名字加上.py的后缀。

(2)为何要使用模块?

如果你退出python解释器然后重新进入,那么你之前定义的函数或者变量都将丢失,因此我们通常将程序写到文件中以便永久保存下来,需要时就通过python test.py方式去执行,此时test.py被称为脚本script。

随着程序的发展,功能越来越多,为了方便管理,我们通常将程序分成一个个的文件,这样做程序的结构更清晰,方便管理。这时我们不仅仅可以把这些文件当做脚本去执行,还可以把他们当做模块来导入到其他的模块中,实现了功能的重复利用

(3)如何使用模块

import

示例文件:spm.py 文件名spam.py,模块名spam

 

#spam.py
print('from the spam.py')

money=1000

def read1():
    print('spam->read1->money',1000)

def read2():
    print('spam->read2 calling read')
    read1()

def change():
    global money
    money=0

模块可以包含可执行的语句和函数的定义,这些语句的目的是初始化模块,它们只在模块名第一次遇到导入import语句时才执行(import语句是可以在程序中的任意位置使用的,且针对同一个模块很import多次,为了防止你重复导入,python的优化手段是:第一次导入后就将模块名加载到内存了,后续的import语句仅是对已经加载大内存中的模块对象增加了一次引用,不会重新执行模块内的语句),如下 

 

#test.py
import spam #只在第一次导入时才执行spam.py内代码,此处的显式效果是只打印一次'from the spam.py',当然其他的顶级代码也都被执行了,只不过没有显示效果.
import spam
import spam
import spam

'''
执行结果:
from the spam.py
'''

每个模块都是一个独立的名称空间,定义在这个模块中的函数,把这个模块的名称空间当做全局名称空间,这样我们在编写自己的模块时,就不用担心我们定义在自己模块中全局变量会在被导入时,与使用者的全局变量冲突 (在模块中定义的变量,只在模块中生效,不影响当前程序的作用)

 

#测试一:money与spam.money不冲突
#test.py
import spam 
money=10
print(spam.money)  在调用模块spam内的代码时,要模块名加.的方式spam.

'''
执行结果:
from the spam.py
1000
'''

 

#测试二:read1与spam.read1不冲突
#test.py
import spam
def read1():
    print('========')
spam.read1()

'''
执行结果:
from the spam.py
spam->read1->money 1000
'''

 

#测试三:执行spam.change()操作的全局变量money仍然是spam中的
#test.py
import spam
money=1
spam.change()
print(money)

'''
执行结果:
from the spam.py
1
'''

总结:首次导入模块spam时会做三件事

 

1.为源文件(spam模块)创建新的名称空间,在spam中定义的函数和方法若是使用到了global时访问的就是这个名称空间。(创建作用域)

2.在新创建的命名空间中执行模块中包含的代码,见初始导入import spam(在该作用域中执行顶级代码)

3.创建名字spam来引用该命名空间(在import spam时其实是定义了一个变量spam,并把spam内的代码绑定到该变量名上)

1 这个名字和变量名没什么区别,都是‘第一类的’,且使用spam.名字的方式可以访问spam.py文件中定义的名字,spam.名字与test.py中的名字来自两个完全不同的地方。

为模块名起别名,相当于m1=1;m2=m1

1 import spam as sm
2 print(sm.money)

 为已经导入的模块起别名的方式对编写可扩展的代码很有用,假设有两个模块xmlreader.py和csvreader.py,它们都定义了函数read_data(filename):用来从文件中读取一些数据,但采用不同的输入格式。可以编写代码来选择性地挑选读取模块,例如

1 if file_format == 'xml':
2     import xmlreader as reader
3 elif file_format == 'csv':
4     import csvreader as reader
5 data=reader.read_date(filename)

在一行导入多个模块

import sys,os,re


from ...import...

从什么模块导入什么功能

对于import spam 在用时spam.read1() 而from spam import read1 在用时可以直接read1()

当在一个程序中同时导入两个模块时

from spm import read1 #导入进来的就是一个名字read1后面绑定着一堆代码,相当于x=1from spam1 import read1 #当在从另外一个模块导入同样的功能read1时会覆盖原来的read1,相当于x=2 此时x就是2
#同样在当前程序中也定义了一个和导入来的功能名相同的功能时,会覆盖导入进来的
def read1():
    print("====>")
read1()
#执行结果:
#from in the spam 这是from spm import read1 是执行的spm模块的顶级代码(无论是from...from..还是import都会执行)
#====>

导入多个属性

from spm import read1,change #用,分隔开
也可以一行一个用括号
from spam import (read1, read2, money)

也支持as

from spam import read1 as read

from spam import * 把spam中所有的不是以下划线(_)开头的名字都导入到当前位置,大部分情况下我们的python程序不应该使用这种导入方式,因为*你不知道你导入什么名字,很有可能会覆盖掉你之前已经定义的名字。而且可读性极其的差,在交互式环境中导入时没有问题。

可以使用__all__来控制*(用来发布新版本)

在spam.py中新增一行

__all__=['money','read1'] #这样在另外一个文件中用from spam import *就这能导入列表中规定的两个名字

把模块当做脚本使用

我们可以通过模块的全局变量__name__来查看模块名:print(__name__)
当做脚本运行:
__name__ 等于'__main__'

当做模块导入:
__name__= '模块名'

作用:用来控制.py文件在不同的应用场景下执行不同的逻辑
if __name__ == '__main__':

  print("当做脚本使用")

这样在import 导入该模块后就不会执行 print("当做脚本使用") 这段代码

模块搜索路径

当模块spam被导入时,解释器首先回去内置的模块中找(看有内置中有同名的不),如果不存在,
就从一个由变量sys.path给出的目录列表中依次寻找spam.py文件。sys.path的初始化的值来自于:
The directory containing the input script (or the current directory when no file is specified).
PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
The installation-dependent default.

需要特别注意的是:我们自定义的模块名不应该与系统内置模块重名。

在初始化后,python程序可以修改sys.path,路径放到前面的优先于标准库被加载。

1 >>> import sys
2 >>> sys.path.append('/a/b/c/d')
3 >>> sys.path.insert(0,'/x/y/z') #排在前的目录,优先被搜索

注意:搜索时按照sys.path中从左到右的顺序查找,位于前的优先被查找,sys.path中还可能包含.zip归档文件和.egg文件,python会把.zip归档文件当成一个目录去处理

包是一种通过使用‘ .模块名 ’来组织python模块名称空间的方式。(函数可以当做工具,模块可以当做工具包,而包就是工具包的集合,可以使用.加模块名的方式使用)

包的导入方式也是两种:import 和from...import....

无论是import形式还是from...import形式,凡是在导入语句中(而不是在使用时)遇到带点的,都要第一时间提高警觉:这是关于包才有的导入语法

包的本质就是一个包含__init__.py文件的目录。

包A和包B下有同名模块也不会冲突,如A.a与B.a来自俩个命名空间

glance/                   #Top-level package

├── __init__.py      #Initialize the glance package

├── api                  #Subpackage for api

│   ├── __init__.py

│   ├── policy.py

│   └── versions.py

├── cmd                #Subpackage for cmd

│   ├── __init__.py

│   └── manage.py

└── db                  #Subpackage for db

    ├── __init__.py

    └── models.py
#文件内容

#policy.py
def get():
    print('from policy.py')

#versions.py
def create_resource(conf):
    print('from version.py: ',conf)

#manage.py
def main():
    print('from manage.py')

#models.py
def register_models(engine):
    print('from models.py: ',engine)

注意事项

1.关于包相关的导入语句也分为import和from ... import ...两种,但是无论哪种,无论在什么位置,在导入时都必须遵循一个原则:凡是在导入时带点的,点的左边都必须是一个包,否则非法。可以带有一连串的点,如item.subitem.subsubitem,但都必须遵循这个原则。

2.对于导入后,在使用时就没有这种限制了,点的左边可以是包,模块,函数,类(它们都可以用点的方式调用自己的属性)。

3.对比import item 和from item import name的应用场景:
如果我们想直接使用name那必须使用后者。

import方法

我们在与包glance同级别的文件中测试

1 import glance.db.models
2 glance.db.models.register_models('mysql') 

from...import方法
需要注意的是from后import导入的模块,必须是明确的一个不能带点,否则会有语法错误,如:from a import b.c是错误语法

我们在与包glance同级别的文件中测试 

1 from glance.db import models
2 models.register_models('mysql')
3 
4 from glance.db.models import register_models
5 register_models('mysql')

__init__.py文件
不管是哪种方式,只要是第一次导入包或者是包的任何其他部分,都会依次执行包下的__init__.py文件(我们可以在每个包的文件内都打印一行内容来验证一下),这个文件可以为空,但是也可以存放一些初始化包的代码。

from glance.api import *

在讲模块时,我们已经讨论过了从一个模块内导入所有*,此处我们研究从一个包导入所有*。

此处是想从包api中导入所有,实际上该语句只会导入包api下__init__.py文件中定义的名字,我们可以在这个文件中定义__all___:

#在__init__.py中定义
x=10

def func():
    print('from api.__init.py')

__all__=['x','func','policy']

此时我们在于glance同级的文件中执行from glance.api import *就导入__all__中的内容(versions仍然不能导入)。

绝对导入和相对导入

我们的最顶级包glance是写给别人用的,然后在glance包内部也会有彼此之间互相导入的需求,这时候就有绝对导入和相对导入两种方式:

绝对导入:以glance作为起始

相对导入:用.或者..的方式最为起始(只能在一个包中使用,不能用于不同目录内)

例如:我们在glance/api/version.py中想要导入glance/cmd/manage.py

在glance/api/version.py

#绝对导入
from glance.cmd import manage
manage.main()

#相对导入
from ..cmd import manage
manage.main()

特别需要注意的是:可以用import导入内置或者第三方模块,但是要绝对避免使用import来导入自定义包的子模块,应该使用from... import ...的绝对或者相对导入,且包的相对导入只能用from的形式。

比如我们想在glance/api/versions.py中导入glance/api/policy.py,有的同学一抽这俩模块是在同一个目录下,十分开心的就去做了,它直接这么做

1 #在version.py中
2 
3 import policy
4 policy.get()

没错,我们单独运行version.py是一点问题没有的,运行version.py的路径搜索就是从当前路径开始的,于是在导入policy时能在当前目录下找到

但是你想啊,你子包中的模块version.py极有可能是被一个glance包同一级别的其他文件导入,比如我们在于glance同级下的一个test.py文件中导入version.py,如下

from glance.api import versions

'''
执行结果:
ImportError: No module named 'policy'
'''

'''
分析:
此时我们导入versions在versions.py中执行
import policy需要找从sys.path也就是从当前目录找policy.py,
这必然是找不到的
'''

单独导入包
单独导入包名称时不会导入包中所有包含的所有子模块,如

#在与glance同级的test.py中
import glance
glance.cmd.manage.main()

'''
执行结果:
AttributeError: module 'glance' has no attribute 'cmd'

'''

解决方法:

1 #glance/__init__.py
2 from . import cmd
3 
4 #glance/cmd/__init__.py
5 from . import manage

执行:

1 #在于glance同级的test.py中
2 import glance
3 glance.cmd.manage.main()

千万别问:__all__不能解决吗,__all__是用于控制from...import * 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2017-02-14 18:13  python-残阳  阅读(194)  评论(0)    收藏  举报