|
发表于 2022-11-17 16:01:47
|
显示全部楼层
- def type_check(correct_type):
- def outer(func):
- def inner(arg):
- if(type(arg) == correct_type): # 在本例中,correct_type 在调用 double() 时是 int,在调用 upper() 时是 str
- return func(arg) # 如果参数符合类型要求,返回对被装饰函数 double(args) 或 upper(args) 函数的调用结果
- else: # 否则,拒绝调用被装饰函数,返回参数类型错误信息
- return "参数类型错误!"
- return inner
-
- return outer
-
-
- print("<<<--- 测试整数 --->>>")
-
- @type_check(int) # 传递给 type_check(correct_type) 形参 correct_type 的实参是 int,在调用 double(x) 时,要求 type(x) == int,否则,参数类型错误
- def double(x):
- return x * 2
-
- print(double(2))
- print(double("2"))
-
- print("\n<<<--- 测试字符串 --->>>")
-
- @type_check(str) # 传递给 type_check(correct_type) 形参 correct_type 的实参是 str,在调用 upper(s) 时,要求 type(s) == str,否则,参数类型错误
- def upper(s):
- return s.upper()
-
- print(upper('I love FishC.'))
- print(upper(250))
复制代码 |
|