函数03

1、装饰器

  • 简单装饰器:是一个闭包,把函数当作参数返回一个替代版的函数。说明白点就是返回函数的函数
  • 复杂装饰器:我也有点不懂,只有代码,你们看代码吧。
  • 通用装饰器:三个概念都是一样的,就是复杂程度不一样
 1 def fun():
 2     print("sunck is a good man")
 3 def outer(fun):
 4     def inner():
 5         print("****************")
 6         fun()
 7     return inner
 8 f = outer(fun)
 9 f()
10 
11 #执行结果
12 ****************
13 sunck is a good man
简单装饰器
 1 def outer(say):
 2     def inner(age):
 3         if age < 0:
 4             age = 0
 5         say(age)
 6     return inner
 7 @outer  #相当于say = outer(say)
 8 def say(age):
 9     print("sunck is %d years old"%(age))
10 # say = outer(say)
11 say(-10)
12 
13 #执行结果
14 sunck is 0 years old
复杂装饰器
 1 def outer(say):
 2     def inner(name,age):
 3         #添加修改的功能
 4         if age < 0:
 5             age=0
 6         # print("&&&&&&&&&&&&&&&&")
 7         say(name,age)
 8     return inner
 9 @outer
10 def say(name,age):  #函数的参数理论上是无限制的,但是实际上最好不要超过6--7个
11     print("my name is %s,I am %d years old"%(name,age))
12 say("xjm",-21)
复杂装饰器

2、变量的作用域

作用域:变量可以使用的范围,程序的变量并不是所有位置都可以用的,访问的权限决定于变量在哪赋值的,

局部作用域

全局作用域

内建作用域

3、异常处理

try:
  print(3 / 0)
except:
  ZeroDivisionError

当程序遇到问题时,不让程序结束,而越过错误,向下运行。

4、断言

def fun(num,div):
    assert (div != 0),"div不能为0"
    return num / div
print(fun(10,0))

#执行结果
Traceback (most recent call last):
  File "D:/学习历程/python/day07/4-异常处理/002-断言.py", line 4, in <module>
    print(fun(10,0))
  File "D:/学习历程/python/day07/4-异常处理/002-断言.py", line 2, in fun
    assert (div != 0),"div不能为0"
AssertionError: div不能为

这里我没有详细说明,后续补充,谢谢!

猜你喜欢

转载自www.cnblogs.com/xjmlove/p/9051686.html
今日推荐