例1、面向对象 Object - Oriented
1 class Student:
2 def __init__(self, name, grade):
3 self.name = name
4 self.grade = grade
5
6 def introduce(self):
7 print("Hi! I'm " + self.name)
8 print("my grade is: " + str(self.grade))
9
10 def improve(self, amount):
11 self.grade += amount
12
13 Tom = Student("Tom", 80)
14 Tom.introduce()
15
16 Tom.improve(10)
17 Tom.introduce()
例2、装饰 Decorators
make_cake = add_candles(make_cake)
1 def add_candles(cake_func):
2 def insert_candles():
3 return cake_func() + "candles"
4 return insert_candles
5
6 def make_cake():
7 return "cake "
8
9 make_cake = add_candles(make_cake)
10
11 print(make_cake())
例3、等价于例2
@add_candles
1 def add_candles(cake_func):
2 def insert_candles():
3 return cake_func() + "candles"
4 return insert_candles
5
6 @add_candles
7 def make_cake():
8 return "cake "
9
10 print(make_cake())