20180417课程笔记

20180417课程笔记

In [7]:
is_odd = lambda n:n%2==1
L = list(filter(is_odd, range(1, 20)))
print(L)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
In [6]:
# 以下代码在 python3下的输出结果可能会有?
#其中random.randint(m,n)输出的值x:m <= x <= n
#f(30)=832040 f(40)=102334155
import random
f = lambda n:1 if n <=2 else f(n-1) + f(n-2)
a = b = [6,8]
a.append(f(random.randint(a[0],a[1])))
print(a,end='')
b.append(f(random.randint(b[0],b[1])))
print(b)
[6, 8, 13][6, 8, 13, 13]
In [ ]:
#1,1,2,3,5,8,13,21
In [20]:
# 以下代码在 python3下的输出结果可能会有?
#其中random.randint(m,n)输出的值x:m <= x <= n
#f(30)=832040 f(40)=102334155
import random
#f = lambda n:1 if n <=2 else f(n-1) + f(n-2)
def f(n):
    if n <= 2:
        return 1
    else:
        return f(n-1)+f(n-2)
a = b = [6,8]
a.append(f(random.randint(a[0],a[1])))
print(a,end='')
b.append(f(random.randint(b[0],b[1])))
print(b)
[6, 8, 13][6, 8, 13, 13]
主调
类型
s=str()
s.
函数名及参数中文注解
strsplit(self, sep, maxsplit)分割
strformat(self,args,kwargs)格式化输出
strcount(self,x,__start,__end统计
strencode(self,encoding,errors)编码
strdecode()解码
strisalpha(self)是否为字母
strisspace(self)是否为空格
strisdigit(self)是否为数字
strstrip(self,chars)去首尾空格
strjoin(self,iterable)链接相加都不对,一般跟列表,把列表拼成字符串,
并以前面主调作为分隔符来合并
In [16]:
a=["a1","a2","3"]
"-".join(a)
print(a)
print("-".join(a))
['a1', 'a2', '3']
a1-a2-3
主调
类型
s=str()
s.
函数名及参数中文注解
strindex(self,sub,__start,__end)打印下标
strstartwith(self,prefix,start,end)后跟字符串,以什么开头
strfind(self,sub,__start,__end)查找,返回下标,找不到返回-1
strreplace(self,old,new,count)以旧的代替为新的
In [18]:
a=["a1","a2","3"]
print("-".join(a).replace("a","b"))
b1-b2-3
主调
类型
s=str()
s.
函数名及参数中文注解
strtitle(self)打印下标
strendswith(self,suffix,start,end)后跟字符串,以什么结束
strlower(self)小写
strupper(self)大写
strisalnum(self)数字和字母
strisdecimal(self)是否只包含十进制字符,偶尔不常用的可以搜一搜,
只存在于unicode对象,定义一个十进制字符串,
只需要在字符串前添加‘u’前缀,“u"123"”?
strcapitalize(self) 
strcenter(self,width,fillchar) 
strexpandtabs(self,tabsize) 
strformat_map(self,map) 
strisidentifier(self) 
strislower(self) 
strisnumeric(self) 
strisprintable(self) 
stristitle(self) 
strisupper(self) 
strljust(self,width,fillchar) 
str  
主调
类型
a=list()
a.
函数名及参数中文注解
listappend(self,object)追加
listcount(self,object)统计
listcopy(self)区分a=b和a=b.copy(),指向的位置不一样
listremove(self,object)删除
listclear(self)清除
listpop(self,index)移除,加上index就是指定删除
listindex(self,object,start,stop)下标
listextend(self,iterable)扩展,加
listsort(self,key,reverse)排序
listreverse(self)翻转
listinsert(self,index,object)插入
主调
类型
b=dict()
b.
函数名及参数中文注解
dictitems(self)返回值是key:value
dictcopy(self) 
dictupdate(self,kwargs)两个字典合并,a.update(b),
相当于把b加到a里面
dictfromkeys(seq,value) 
dictvalues(self) 
dictkeys(self) 
dictclear(self) 
MutableMappingpop(self,k,default) 
Mappingget(self,k,default)通过key获取到value
dictsetdefault(self,k,default)设定一个默认值
dictpopitem(self) 

装饰器

装饰器的作用:
装饰器本质上是一个Python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象。它经常用于有切面需求的场景,比如:插入日志、性能测试、事务处理、缓存、权限校验等场景。装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大量与函数功能本身无关的雷同代码并继续重用。

装饰器的作用简单点说:就是不改变原来函数本身,在函数的前面或者后面增加一些额外的功能。

场景:京东购物

在了解装饰器之前,我们先来了解一个callable函数

说明:

  1. 方法用来检测对象是否可被调用,可被调用指的是对象能否使用()括号的方法调用。 def a(): pass callable(a)
  2. 可调用对象,在实际调用也可能调用失败;但是不可调用对象,调用肯定不成功。
  3. 类对象都是可被调用对象,类的实例对象是否可调用对象,取决于类是否定义了call方法

编码规范(markdown 双空格软回车,双回车分段)
def 首字母小写后跟驼峰
class 首字母大写后跟驼峰

In [28]:
def hello():
    print("hello world!")
a = hello()
print(type(a))
print("##")
b = hello
#这里区分不了,下文就会学不懂
# a 代表什么 hello函数把返回值给到a None
# b 代表什么 b是一个函数 
b()
print(type(b))
hello world!
<class 'NoneType'>
##
hello world!
<class 'function'>
装饰器的作用:在不改变源代码的情况下,给现有的函数增加新的功能  
装饰器通过@进行使用  
@startEnd  相当于  hello = startEnd(hello())  
实际相当于hello = startEnd(hello)  
相当于把函数作为参数传给@startEnd,再重命名为hello,不能有括号  
当你调用hello`()`的时候,就相当于调用了startEnd(hello())`()`,注意这里的括号  
作为对象传参的时候,不加括号
In [32]:
def startEnd(fun):
    def wraper():
        print("!!!!!!!!!!!start!!!!!!!!!!!")
        fun()
        print("!!!!!!!!!!!end!!!!!!!!!!!!!")
    return wraper
# 返回值wraper函数,不能返回一个括号(wraper只是名字)
# hello() 相当于执行wraper()
# 执行wraper等于执行参数的fun,并得到fun()
#可以利用debug模式追踪
'''  
hello(),已经被装饰,进入装饰器内部->  
startEnd(hello()),并def段生成wraper函数,因为没有执行体,直接到return了->  
return wrapper,即执行wrapper(),并def段生成fun,也就是参数的hello,  
此时hello仅作为一个函数类型的传参->  
进入wrapper内部->  
before fun()->  
fun()->  
after fun()  
'''
# 重新举例
# 1. a = startEnd(hello),a等于是startEnd(hello)的返回值
# 2. hello = a
# 3. 调用hello(),相当于调用的a
# 4. 放到def startEnd(fun):场景,就相当于得到并调用返回值wraper
#装饰器行开始
@startEnd
def hello():
    print("hello world!")
#装饰器行结束
a = hello()
print(type(a))
print("#")
b = hello
print("##")
#这里区分不了,下文就会学不懂
# a 代表什么 hello函数把返回值给到a None
# b 代表什么 b是一个函数 
b()
print(type(b))
!!!!!!!!!!!start!!!!!!!!!!!
hello world!
!!!!!!!!!!!end!!!!!!!!!!!!!
<class 'NoneType'>
#
##
!!!!!!!!!!!start!!!!!!!!!!!
hello world!
!!!!!!!!!!!end!!!!!!!!!!!!!
<class 'function'>
为什么要出装饰器设计,等于是借用类似的特性,达到a=hello(),就可以变成a=装饰器hello()
In [23]:
#装饰器例子:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import datetime
def hello(fun):
        def preHello():
            print("#####start#####")
            fun()
            print("#####end#####")
        return preHello
@hello
def myTime():
        now = datetime.datetime.now()
        print(now)
myTime()
#####start#####
2018-04-20 22:55:52.679533
#####end#####

装饰器带参数,和被装饰函数带参数

In [39]:
##被装饰函数带参数
def startEnd(fun):
    def wraper(name):
        print("!!!!!!!!!!!start!!!!!!!!!!!")
        fun(name)
        print("!!!!!!!!!!!end!!!!!!!!!!!!!")
    return wraper
'''  
hello("sss"),已经被装饰,进入装饰器内部->  
startEnd(hello("sss")),并def段生成wraper函数,因为没有执行体,直接到return了->  
return wrapper,
此时将装饰器解开,参数传递给wrapper("sss"),def段生成fun,也就是函数为参数的hello,  
hello():此时hello仅作为一个函数类型的传参->  
进入wrapper内部->  
before fun("sss")->  
fun("sss"),fun()等于执行没有被装饰的函数执行体->  
after fun("sss")  
'''
#装饰器行开始
@startEnd
def hello(name):
    print("hello {0}".format(name))
#装饰器行结束
a = hello("sss")
print(type(a))
print("#")
b = hello
print("##")
#这里区分不了,下文就会学不懂
# a 代表什么 hello函数把返回值给到a None
# b 代表什么 b是一个函数 
b("sss")
print(type(b))
!!!!!!!!!!!start!!!!!!!!!!!
hello sss
!!!!!!!!!!!end!!!!!!!!!!!!!
<class 'NoneType'>
#
##
!!!!!!!!!!!start!!!!!!!!!!!
hello sss
!!!!!!!!!!!end!!!!!!!!!!!!!
<class 'function'>
In [40]:
##装饰器带参数
def needStartEnd(author):
    def startEnd(fun):
        def wraper(name):
            print("needStartEnd(author):{0}".format(author))
            print("!!!!!!!!!!!start!!!!!!!!!!!")
            fun(name)
            print("!!!!!!!!!!!end!!!!!!!!!!!!!")
        return wraper
    return startEnd
'''  
hello("sss"),已经被装饰,进入装饰器内部->  
startEnd(hello("sss")),并def段生成wraper函数,因为没有执行体,直接到return了->  
return wrapper,
此时将装饰器解开,参数传递给wrapper("sss"),def段生成fun,也就是函数为参数的hello,  
hello():此时hello仅作为一个函数类型的传参->  
进入wrapper内部->  
before fun("sss")->  
fun("sss"),fun()等于执行没有被装饰的函数执行体->  
after fun("sss")  
'''
#装饰器行开始
@needStartEnd("ttt")# 等于多包一层,用于处理参数,并且优先执行传参处理
def hello(name):
    print("hello {0}".format(name))
#装饰器行结束
a = hello("sss")
print(type(a))
print("#")
b = hello
print("##")
#这里区分不了,下文就会学不懂
# a 代表什么 hello函数把返回值给到a None
# b 代表什么 b是一个函数 
b("sss")
print(type(b))
needStartEnd(author):ttt
!!!!!!!!!!!start!!!!!!!!!!!
hello sss
!!!!!!!!!!!end!!!!!!!!!!!!!
<class 'NoneType'>
#
##
needStartEnd(author):ttt
!!!!!!!!!!!start!!!!!!!!!!!
hello sss
!!!!!!!!!!!end!!!!!!!!!!!!!
<class 'function'>
In [57]:
##装饰器带参数
def needStartEnd(author):
    def startEnd(fun):
        def wraper(name):
            print("needStartEnd(author):{0}".format(author))
            print("!!!!!!!!!!!start!!!!!!!!!!!")
            print("\\\\\\\\")
            fun(name)
            print("")
            print("!!!!!!!!!!!end!!!!!!!!!!!!!")
        return wraper
    return startEnd
'''
needStartEnd("xxx")(hello)("uuu")->
return startEnd->
startEnd("xxx")(hello)("uuu")->
return wraper->此时还没有解除装饰器函数传参
进入wrapper内部->  
before fun("uuu")-> author装饰器传参 "xxx"->
fun("uuu"),fun()等于一个装饰器->  
before fun("uuu")-> author装饰器自带 "ttt"->
fun("uuu"),fun()等于原函数-> "uuu"
after fun("uuu")->装饰器结束
after fun("uuu")->函数wraper结束
'''
#装饰器行开始
@needStartEnd("ttt")# 等于多包一层,用于处理参数,并且优先执行传参处理
def hello(name):
    print("hello {0}".format(name))
#装饰器行结束
x = needStartEnd("xxx")(hello)
x("uuu")
print("#")
x = needStartEnd("xxx")
x("uuu")
print("##")
x = needStartEnd
x("uuu")
print("###")
needStartEnd(author):xxx
!!!!!!!!!!!start!!!!!!!!!!!
\\\\
needStartEnd(author):ttt
!!!!!!!!!!!start!!!!!!!!!!!
\\\\
hello uuu

!!!!!!!!!!!end!!!!!!!!!!!!!

!!!!!!!!!!!end!!!!!!!!!!!!!
#
##
###

找到装饰器重复两次的问题

等于说是传参的hello,是一个装饰器名,不是函数名
但是传参这么搞不方便,没找到相关传参的资料

In [33]:
#说明:
#装饰器的@hello 就相当于执行hello函数,参数为myTime  即:hello(myTime), 返回结果为preHello对象, 然后把返回结果赋值给myTime变量,因为myTime是可被调用的。所以直接myTime()
#myTime = hello(myTime)
#myTime()
#带参数的装饰器:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time    : 2017/11/3 14:35
# @Author  : lingxiangxiang
# @File    : test4.py
import datetime
def author(name):
    def hello(fun):
        def preHello():
            print("The Author is {0}".format(name))
            print("#####start#####")
            fun()
            print("#####end#####")
        return preHello
    return hello
@author("lingxiangxiang")
def myTime():
    now = datetime.datetime.now()
    print(now)
myTime()
The Author is lingxiangxiang
#####start#####
2018-04-20 23:57:21.783538
#####end#####
 
         
基于类的装饰器
装饰器函数其实是这样一个接口约束,它必须接受一个callable对象作为参数,然后返回一个callable对象。在Python中一般callable对象都是函数,但也有例外。只要某个对象重载了__call__()方法,那么这个对象就是callable的。
回到装饰器上的概念上来,装饰器要求接受一个callable对象,并返回一个内部的callable对象
,那么用类来实现也是也可以的。我们可以让类的构造函数__init__()接受一个函数,然后重载__call__()并返回一个函数,也可以达到装饰器函数的效果。
In [ ]:
 
          
基于类的装饰器例子:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
 
import datetime
 
class hello(object):
    def __init__(self, func):
        self.func = func
 
    def __call__(self, *args, **kwargs):
        print("start")
        self.func(*args, **kwargs)
        print("end")
 
@hello
def say_time(name):
    print("hello {0}, now is: {1}".format(name, datetime.datetime.now()))
 
say_time("lingxiangxiang")
In [ ]:
 
          
带参数的类装饰器:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time    : 2017/11/3 14:35
# @Author  : lingxiangxiang
# @File    : test4.py
import datetime
 
class hello(object):
    def __init__(self, author):
        self.author = author
 
    def __call__(self, func):
        def wrapper( *args, **kwargs):
            print("The author is {0}".format(self.author))
            print("start")
            func(*args, **kwargs)
            print("end")
        return wrapper
 
@hello("lingxiangxiang")
def say_time(name):
    print("hello {0}, now is: {1}".format(name, datetime.datetime.now()))
 
say_time("猿课")
In [ ]:
@staticmethod和@classmethod
一般来说,要使用某个类的方法,需要先实例化一个对象再调用方法。
而使用@staticmethod@classmethod,就可以不需要实例化,直接类名.方法名()来调用。
这有利于组织代码,把某些应该属于某个类的函数给放到那个类里去,同时有利于命名空间的整洁。
@staticmethod不需要表示自身对象的self和自身类的cls参数,就跟使用函数一样。
@classmethod也不需要self参数,但第一个参数需要是表示自身类的cls参数。
如果在@staticmethod中要调用到这个类的一些属性方法,只能直接类名.属性名或类名.方法名。
@classmethod因为持有cls参数,可以来调用类的属性,类的方法,实例化对象等,避免硬编码。
self和cls的区别不是强制的,只是PEP8中一种编程风格,self通常用作实例方法的第一参数,cls通常用作类方法的第一参数。即通常用self来传递当前类对象的实例,cls传递当前类对象。
In [ ]:
乘法口诀:
 print('\n'.join(' '.join("{0}x{1}={2}".format(x, y, x*y) for x in xrange(1, y+1) )for y in xrange(1, 10)))
 
         
## 模块,类,函数的区别
模块 > 类 > 函数
### 目录和模块的区别
Modole:模块必须有\_\_init\_\_.py文件,也可以叫一个包  
目录没有这个文件  
只有包里面的文件名可以引入  
题目4:输入某年某月某日,判断这一天是这一年的第几天?  
题目14:一个数如果恰好等于它的因子之和,这个数就称为“完数”。例如6=1+2+3,.编程找出1000以内的所有完数。
In [ ]:
#下方代码存在于一个.py文件中
#可以import一个*.py的*来调用其他需要的库
class Action():#类
    def hello(self):#函数
        print("hello world")
actionSelect = ActionSelect()
#不用new一个
#如上取名不易混淆
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值