将参数传递给函数时如何定义条件? 在python中更有效地编码

问题描述

在这代码中,我有两个函数 shoppingAshoppingS,它们共享多行。但是,我传递的参数略有不同。一个需要两个额外的参数。我想知道如何通过只有一个购物函数来提高代码效率,如果 model_index == 0 我可以传递前两个参数,如果 model_index = 传递四个参数= 1

我应该注意,由于这些参数将在其他函数中使用,我不想定义全局。

model_index = 0

def shoppingA(agemean,agestd):
    global sum_prod,sum_sales
    age = agemean - agestd
    sum_prod += 1
    sum_sales += 20
    if sum_prod < 5 and age < 7:
        print("insufficient")
    
    
def shoppingS(agemean,agestd,randstd,randmean):
    global sum_prod,sum_sales
    age = agemean * randmean - agestd * randstd
    sum_prod += 1
    sum_sales += 1
    if sum_prod < 5 and age <7:
        print("insufficient")    
############################
def main(parameters):
    global sum_prod,sum_sales
    sum_prod = 0
    sum_sales = 0
    agemean = parameters[0]
    agestd = parameters[1]
    if model_index != 0: 
        randstd = parameters[2]
        randmean = parameters[3]
    if model_index == 0:
        shoppingA(agemean,agestd)
    else:
        shoppingS(agemean,randmean)       
###########################        
if model_index == 0:
    agemean = 5     
    agestd = 0.508           
    parameters = [agemean,agestd]
if model_index == 1:
    agemean = 8      
    agestd = 0.4       
    randstd = 9  
    randmean = 24.7    
    parameters = [agemean,randmean]   
if __name__ == "__main__":
    obj = main(parameters)

换句话说,我想做一些类似于你在下面看到的,参数可以以灵活的方式传递。

model_index = 0

def shopping():
    if model_index == 0:
        shopping(agemean,agestd)
    else:
        shopping(agemean,randmean)
    global sum_prod,sum_sales
    if model_index == 0:
        age = agemean - agestd
    else:
        age = agemean * randmean - agestd * randstd
    sum_prod += 1
    sum_sales += 20
    if sum_prod < 5 and age < 7:
        print("not_insufficient")

    
############################
def main(parameters):
    global sum_prod,sum_sales
    sum_prod = 0
    sum_sales = 0
    agemean = parameters[0]
    agestd = parameters[1]
    if model_index != 0: 
        randstd = parameters[2]
        randmean = parameters[3]
    shopping()  #####Only one shopping function
      
###########################        
if model_index == 0:
    agemean = 5     
    agestd = 0.508           
    parameters = [agemean,randmean]   
if __name__ == "__main__":
    obj = main(parameters)

非常感谢

解决方法

在这两种情况下,您都可以传递 4 个参数。但是如果 model_index 为 0,则将 1 作为最后 2 个参数传递,如下所示:

shoppingS(agemean,agestd,1,1);

因为您将agemean乘以第三个参数,将agestd乘以第四个参数,然后您正在做减法运算。所以当第 3 和第 4 个参数为 1 时,乘法不会改变第 1 个和第 2 个参数的值。