装饰器系列:
[1]. Python装饰器(decorator)系列 — 面向对象以及装饰器
[2]. Python装饰器(decorator)系列 — 编写无参数的装饰器
[3]. Python装饰器(decorator)系列 — 编写带参数的装饰器
类(class):是对现实世界中一些事物的封装
类中包含类的属性和类方法
通过小栗子感受一下吧:
class Student:
def __init__(self, name, grade): # 构造函数中包含类的属性
self.name = name
self.grade = grade
def introduce(self): # 类方法
print("Hey,My name is", self.name)
print("My grade is", self.grade)
def improve(self, amount):
self.grade += amount
jim = Student("jim", 88)
jim.introduce()
print() # 利用Python中print本身的换行属性来
jim.improve(10)
jim.introduce()
结果为:
Hey,My name is jim
My grade is 88
Hey,My name is jim
My grade is 98
cake and candles:
def add_candles(cake_func):
def insert_candel():
return cake_func() + ' candles'
return insert_candel
def make_cake():
return 'cake'
get_cake = add_candles(make_cake)
print(make_cake())
print(get_cake())
结果为:
cake
cake candles
加入装饰器 decorator
装饰器是在主题函数的基础功能上,可以灵活加入我们想要增加的新功能
def add_candles(cake_func):
def insert_candel():
return cake_func() + ' candles'
return insert_candel
@add_candles
def make_cake():
return 'cake'
print(make_cake())
结果为:
cake candles