【问题标题】:How do you check if the user passes at least one of the arguments?你如何检查用户是否至少传递了一个参数?
【发布时间】:2020-05-22 15:18:29
【问题描述】:

有时一个对象可以由不同类型的参数构成。例如,可以通过提供其半径或周长来定义圆形对象。如何编写__init__ 方法,以便在用户输入半径和输入圆周时都构造一个圆形对象。

我想出了这个,但它看起来太臃肿了:

class Circle:

    def __init__(self, radius = None, circumference = None):

        # Calculate area when user provides circumference
        if radius is None and circumference is not None:
            self.area = (circumference**2) / (4*3.14)

        # Calculate area when user provides radius
        elif radius is not None and circumference is None:
            self.area = (radius ** 2) * 3.14

        # Raise error if neither radius nor circumference or both are provided
        else:
            raise TypeError("Pass either a radius or circumference argument value")

您是否将参数默认为None,或者是否有针对这种情况设计的合适的 Python 方式?

另外,在这种情况下使用TypeError 是否正确?

我什至不知道半径和周长在这里是否被视为可选参数或必需参数,因为至少其中一个是必需的。有人可以请教我吗?

【问题讨论】:

    标签: python parameters optional-parameters


    【解决方案1】:

    如果提供两个参数,我只会优先考虑两个参数之一。应该是这样的:

    class Circle:
    
        def __init__(self, radius = None, circumference = None):
    
            # Calculate area when user provides circumference
            if circumference:
                self.area = (circumference**2) / (4*3.14)
    
            # Calculate area when user provides radius
            elif radius:
                self.area = (radius ** 2) * 3.14
    
            # Raise error if neither radius nor circumference or both are provided
            else:
                raise TypeError("Pass either a radius or circumference argument value")
    

    【讨论】:

    • 善用if x而不是if x is not None。
    【解决方案2】:

    假设,您想回答标题问题:

    您的代码看起来不错,但您可以使用**kwargs 参数而不是列出所有可能的候选者,无需详细说明即可轻松检查其中是否包含某些内容。

    对于一般方法:

    我猜你的功能分解增加了复杂性:为什么在构造函数中进行计算?考虑这个接口:

       c = Circle()
       c.setRadius(4.5) # alternatively: c.setCircumference(13.7)
       print(c.getArea())
    

    【讨论】:

      猜你喜欢
      • 2022-01-11
      • 2022-06-17
      • 2021-05-14
      • 1970-01-01
      • 2011-07-05
      • 1970-01-01
      • 1970-01-01
      • 2012-05-28
      • 1970-01-01
      相关资源
      最近更新 更多