#! /usr/bin/env python # -*- coding:utf-8 -*- def my_sum(*arg): return sum(arg) def my_average(*arg): return sum(arg)/len(arg) #print(my_sum(1,2,3,4,5)) #print(my_sum(1,2,3,4,5,'6')) #报错。不支持的类型 #print(my_average(1,2,3,4,5)) #print(my_average()) # 报错长度为0除以0所以报错 #为了提高代码的健壮性需要加入判断 ''' def my_sum(*arg): if len(arg) == 0: return 0 for val in arg: if not isinstance(val,int): return 0 return sum(arg) def my_average(*arg): if len(arg) == 0: return 0 for val in arg: if not isinstance(val,int): return 0 return sum(arg)/len(arg) ''' # 为了提高上述判断代码的复用性,可以使用闭包来实现 def my_sum(*arg): return sum(arg) def my_average(*arg): return sum(arg)/len(arg) def dec(func): def in_dec(*arg): if len(arg) == 0: return 0 for val in arg: if not isinstance(val,int): return 0 return func(*arg) return in_dec my_sum = dec(my_sum) #sum = my_sum(1,2,3) my_average = dec(my_average) print(my_sum(1,2,3,4,5)) print(my_sum(1,2,3,4,5,'6')) print(my_average(1,2,3,4,5)) print(my_average())