【问题标题】:How to define a function with two possible variations of arguments?如何定义具有两种可能的参数变体的函数?
【发布时间】:2018-06-22 05:26:26
【问题描述】:

我正在尝试在 python 中定义一个函数,其中该函数有两组可能的参数。我正在编写一个代码来确定整体课程成绩,并且取决于他们是否改变标准课程权重取决于我有多少个参数想发送到计算成绩的函数。如果他们不改变标准权重,我只想传递两个参数(测试分数和实验室分数)。如果他们改变权重,我想传递四个参数(测试分数、实验室分数、实验室重量和测试重量)。总的来说,我不确定我将如何定义所述函数,因为通常的做法是将所有参数放在功能开始。

GradeWeight=raw_input('Enter C to change weights or D to use default weights.')
GradeWeight=GradeWeight.upper()
if GradeWeight=='D':
    grade_calculator(a=LabScores,b=TestScores)
elif GradeWeight=='C':
    LabWeight=float(input('What is the lab weight percentage?(without the %)'))
    TestWeight=float(input('What is the test weight percentage?(without the %)'))
    grade_calculator(a=LabScores,b=TestScores,c=LabWeight,d=TestWeight)
def grade_calculator():

【问题讨论】:

标签: python function


【解决方案1】:

有可能:

def grade_calculator(**kwargs):
  if 'c'  in kwargs or 'd' in kwargs:
    #do your thing
  else:
    # do your other thing

【讨论】:

    【解决方案2】:

    我假设您来自一种允许重载的语言,让您可以执行以下操作:

    public int test(int one, int two)
    public int test(int one, int two, int three)
    

    不幸的是,Python 不允许这样做。最简单的方法如下。

    def my_method(self, parameter_A, parameter_B=None):
       if isinstance(parameter_B, int):
         print parameter_A * parameter_B
       else:
         print parameter_A
         if parameter_B is not None:
           print parameter_B
    

    本质上,您正在测试是否给出了第二个参数。如果没有给出(或给出为 None,Python 的 null 等效项),则不使用此参数。但是,如果确实如此,则代码会对其进行评估。本质上,这是一个 if 和 else if 语句的游戏。

    您可以阅读here 更多关于 Python 中缺少函数重载的信息。这很麻烦,特别是因为它是 OOP 语言应该具备的,但它是 Python 的少数缺点之一。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-23
      • 1970-01-01
      • 2011-01-08
      • 1970-01-01
      • 2022-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多