In [7]:
is_odd = lambda n:n%2==1
L = list(filter(is_odd, range(1, 20)))
print(L)
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)
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)
主调 类型 s=str() s. | 函数名及参数 | 中文注解 |
---|---|---|
str | split(self, sep, maxsplit) | 分割 |
str | format(self,args,kwargs) | 格式化输出 |
str | count(self,x,__start,__end | 统计 |
str | encode(self,encoding,errors) | 编码 |
str | decode() | 解码 |
str | isalpha(self) | 是否为字母 |
str | isspace(self) | 是否为空格 |
str | isdigit(self) | 是否为数字 |
str | strip(self,chars) | 去首尾空格 |
str | join(self,iterable) | 链接相加都不对,一般跟列表,把列表拼成字符串, 并以前面主调作为分隔符来合并 |
In [16]:
a=["a1","a2","3"]
"-".join(a)
print(a)
print("-".join(a))
主调 类型 s=str() s. | 函数名及参数 | 中文注解 |
---|---|---|
str | index(self,sub,__start,__end) | 打印下标 |
str | startwith(self,prefix,start,end) | 后跟字符串,以什么开头 |
str | find(self,sub,__start,__end) | 查找,返回下标,找不到返回-1 |
str | replace(self,old,new,count) | 以旧的代替为新的 |
In [18]:
a=["a1","a2","3"]
print("-".join(a).replace("a","b"))
主调 类型 s=str() s. | 函数名及参数 | 中文注解 |
---|---|---|
str | title(self) | 打印下标 |
str | endswith(self,suffix,start,end) | 后跟字符串,以什么结束 |
str | lower(self) | 小写 |
str | upper(self) | 大写 |
str | isalnum(self) | 数字和字母 |
str | isdecimal(self) | 是否只包含十进制字符,偶尔不常用的可以搜一搜, 只存在于unicode对象,定义一个十进制字符串, 只需要在字符串前添加‘u’前缀,“u"123"”? |
str | capitalize(self) | |
str | center(self,width,fillchar) | |
str | expandtabs(self,tabsize) | |
str | format_map(self,map) | |
str | isidentifier(self) | |
str | islower(self) | |
str | isnumeric(self) | |
str | isprintable(self) | |
str | istitle(self) | |
str | isupper(self) | |
str | ljust(self,width,fillchar) | |
str |
主调 类型 a=list() a. | 函数名及参数 | 中文注解 |
---|---|---|
list | append(self,object) | 追加 |
list | count(self,object) | 统计 |
list | copy(self) | 区分a=b和a=b.copy(),指向的位置不一样 |
list | remove(self,object) | 删除 |
list | clear(self) | 清除 |
list | pop(self,index) | 移除,加上index就是指定删除 |
list | index(self,object,start,stop) | 下标 |
list | extend(self,iterable) | 扩展,加 |
list | sort(self,key,reverse) | 排序 |
list | reverse(self) | 翻转 |
list | insert(self,index,object) | 插入 |
主调 类型 b=dict() b. | 函数名及参数 | 中文注解 |
---|---|---|
dict | items(self) | 返回值是key:value |
dict | copy(self) | |
dict | update(self,kwargs) | 两个字典合并,a.update(b), 相当于把b加到a里面 |
dict | fromkeys(seq,value) | |
dict | values(self) | |
dict | keys(self) | |
dict | clear(self) | |
MutableMapping | pop(self,k,default) | |
Mapping | get(self,k,default) | 通过key获取到value |
dict | setdefault(self,k,default) | 设定一个默认值 |
dict | popitem(self) |
装饰器的作用:
装饰器本质上是一个Python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象。它经常用于有切面需求的场景,比如:插入日志、性能测试、事务处理、缓存、权限校验等场景。装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大量与函数功能本身无关的雷同代码并继续重用。
装饰器的作用简单点说:就是不改变原来函数本身,在函数的前面或者后面增加一些额外的功能。
场景:京东购物
在了解装饰器之前,我们先来了解一个callable函数
说明:
- 方法用来检测对象是否可被调用,可被调用指的是对象能否使用()括号的方法调用。 def a(): pass callable(a)
- 可调用对象,在实际调用也可能调用失败;但是不可调用对象,调用肯定不成功。
- 类对象都是可被调用对象,类的实例对象是否可调用对象,取决于类是否定义了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))
装饰器的作用:在不改变源代码的情况下,给现有的函数增加新的功能
装饰器通过@进行使用
@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
#装饰器行开始
def hello():
print("hello world!")
#装饰器行结束
a = hello()
print(type(a))
print("#")
b = hello
print("##")
#这里区分不了,下文就会学不懂
# a 代表什么 hello函数把返回值给到a None
# b 代表什么 b是一个函数
b()
print(type(b))
In [23]:
#装饰器例子:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import datetime
def hello(fun):
def preHello():
print("#####start#####")
fun()
print("#####end#####")
return preHello
def myTime():
now = datetime.datetime.now()
print(now)
myTime()
装饰器带参数,和被装饰函数带参数
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")
'''
#装饰器行开始
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))
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")
'''
#装饰器行开始
"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))
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结束
'''
#装饰器行开始
"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("###")
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
"lingxiangxiang") (
def myTime():
now = datetime.datetime.now()
print(now)
myTime()
基于类的装饰器
装饰器函数其实是这样一个接口约束,它必须接受一个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")
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
"lingxiangxiang") (
def say_time(name):
print("hello {0}, now is: {1}".format(name, datetime.datetime.now()))
say_time("猿课")
In [ ]:
@classmethod
一般来说,要使用某个类的方法,需要先实例化一个对象再调用方法。
而使用@staticmethod或@classmethod,就可以不需要实例化,直接类名.方法名()来调用。
这有利于组织代码,把某些应该属于某个类的函数给放到那个类里去,同时有利于命名空间的整洁。
@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一个
#如上取名不易混淆