第三章 函数

python内置函数

print(abs(-22))#取绝对值
>>>22

print(all([1,2,'']))#所有为真即为真,0,空,none为false
>>>False

print(any([1,2,''])) #只要有一个为真,即为真
>>>True

print(bin(20)) #10进制转二进制
>>>0b100

这三种全返回False,其他的都是True
print(bool())
print(bool(None))
print(bool(0))

print(bytes("你好","utf-8"))#字符转字节
>>>b'\xe4\xbd\xa0\xe5\xa5\xbd'  6个字节
print(bytes("你好","utf-8").decode("utf-8"))#解码
print(bytes("你好","gbk"))
>>>b'\xc4\xe3\xba\xc3'   1个字符两个字节
print(bytes("你好","gbk").decode("gbk"))

print(chr(46))#ascli码

print(dir("chr"))#打印某一个对象的方法

print(divmod(10,3))#取余

dic={"name":"alex"}
print(str(dic))

#可hash的数据类型即不可变的数据类型,不可hash的数据类型即可变的数据类型
#hash特性,得出来的值长度是不变的,值不可反推
name="alex"
print(hash(name))

print(help(all))#打印方法帮助
name = "哈哈哈哈哈哈哈哈哈"
print(globals())
print(__file__)

l=[1,20,3,50,-5,16]#最大值
print(max(l))

 


装饰器

高阶函数定义
1.函数接收的参数是一个函数名
2.函数的返回值是一个函数名
3.满足上述条件任意一个,都可称之为高阶函数
(1)
import time
def foo():
    time.sleep(3)
    print("hell,你好")
def test(func):
    start_time=time.time()
    func()
    stop_time=time.time()
    print("函数运行时间是%s"%(stop_time-start_time))

test(foo)
(2)
def foo():
    print("nihao")
def test(func):
    return func
# res=test(foo)
# res()
foo=test(foo)
foo()
(3)不修改foo源代码,不修改foo调用方式
import time
def foo():
    time.sleep(3)
    print("nihao")
def test(func):
    return func
def timer(func):
    start_time = time.time()
    func()
    stop_time=time.time()
    print("函数运行时间是%s"%(stop_time-start_time))
    return func
foo=timer(foo)
函数嵌套
def father(name):
    print('from father %s' %name)
    def son():

        print('from son')
        def grandson():
            print('from grandson')
        grandson()
    son()

father('王琦渊')
 1 装饰器实现,有返回值的
 2 import time
 3 def timer(func):
 4     def wraper():
 5         start_time=time.time()
 6         res=func()#就是在运行test()
 7         stop_time=time.time()
 8         print("运行时间是%s"%(stop_time-start_time))
 9         return res
10     return wraper
11 
12 @timer# 相当于test=timer(test)#返回的是wraper的内存地址
13 def test():
14     time.sleep(3)
15     return "这是test的返回值"
16 
17 res=test()#就是在运行wrapper
18 print(res)#wrapper的返回值
19 
20 装饰器实现,加参数的
21 import time
22 def timer(func):
23     def wraper(*args,**kwargs):
24         start_time=time.time()
25         res=func(*args,**kwargs)#就是在运行test()
26         stop_time=time.time()
27         print("运行时间是%s"%(stop_time-start_time))
28         return res
29     return wraper
30 @timer# 相当于test=timer(test)#返回的是wraper的内存地址,所有修改wraper就达到加参数的作用
31 def test(name,age):
32     time.sleep(3)
33     print("test函数运行完毕,名字是%s,年龄是%d"%(name,age))
34     return "这是test的返回值"
35 @timer
36 def test1(name,age,gender):
37     time.sleep(3)
38     print("test1函数运行完毕,名字是%s,年龄是%d,性别是%s"%(name,age,gender))
39     return "这是test1的返回值"
40 
41 res=test("wangqiyuan",18)#就是在运行wrapper
42 res=test1("wangqiyuan",18,"man")
43 print(res)#wrapper的返回值

 

posted on 2017-05-26 16:11  法海降妖  阅读(109)  评论(0编辑  收藏  举报