一、背景
大量的if … elif…代码非常难看,也很难维护。 扩展不太方便
二、优化方案
1、正常写法
def discount_algorithm ( user_role) :
if user_role == 'admin' :
discount = 0.1
return discount
elif user_role == 'msp' :
discount = 0.3
return discount
elif user_role == 'tenant' :
discount = 0.5
return discount
elif user_role == 'number' :
discount = 0.7
return discount
else :
discount = 1
return discount
user_role = 'admin'
discount = discount_algorithm( user_role)
2、使用字典
def get_admin_discount ( ) :
pass
def get_msp_discount ( ) :
pass
def get_tenant_discount ( ) :
pass
def get_number_discount ( ) :
pass
def get_default_discount ( ) :
pass
user_discount_map = {
'admin' : get_admin_discount( ) ,
'msp' : get_msp_discount( ) ,
'tenant' : get_tenant_discount( ) ,
'number' : get_number_discount( ) ,
'default' : get_default_discount( ) ,
}
discount = user_discount_map[ user_role]
3、使用反射
class DiscountAlgorithm ( ) :
def get_admin_discount ( self) :
pass
def get_msp_discount ( self) :
pass
def get_tenant_discount ( self) :
pass
def get_number_discount ( self) :
pass
def get_default_discount ( self) :
pass
def get_discount ( self, user_role) :
return getattr ( self, user_role) ( )
DiscountAlgorithm( ) . get_discount( 'get_msp_discount' )
三、小结
正常写法适合确定的只有2-3个if条件的情况 字典适合代码量比较小的 反射适合代码量比较多的