简体   繁体   English

你如何检查用户是否至少传递了一个参数?

[英]How do you check if the user passes at least one of the arguments?

Sometimes an object can be constructed by different types of arguments.有时一个对象可以由不同类型的参数构造。 For example, a circle object can be defined either by providing its radius or its circumference.例如,可以通过提供半径或周长来定义圆形对象。 How do I write the __init__ method so that it constructs a circle object both when the user enters a radius and when they enter a circumference.我如何编写__init__方法,以便在用户输入半径和输入圆周时构造一个圆对象。

I came up with this but it looks too bloated:我想出了这个,但它看起来太臃肿了:

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")

Do you default the parameters to None or is there a proper Python way designed for this scenario?您是否将参数默认为None或者是否有为此场景设计的适当 Python 方式?

Also, is the use of TypeError correct in this case?另外,在这种情况下使用TypeError是否正确?

I don't even know if radius and circumference are considered optional or required arguments here since at least one of them is somehow required.我什至不知道这里的半径和周长是否被认为是可选的或必需的参数,因为它们中至少有一个是必需的。 Can someone enlighten me please?有人可以启发我吗?

I would just prioritize one of both arguments if two are provided.如果提供了两个论点,我只会优先考虑其中一个论点。 It would be something like this:它会是这样的:

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")

Assuming, you want the the title question answered:假设您希望回答标题问题:

Your code seems fine, but you could use **kwargs parameter instead of listing all possible candidates, which can be checked for containing something easily without going into details.您的代码看起来不错,但您可以使用**kwargs参数而不是列出所有可能的候选者,可以轻松检查是否包含某些内容而无需详细说明。

For the general approach:对于一般方法:

I guess your breakdown of functionality adds to complexity: why do the computation stuff in the constructor?我猜你的功能分解增加了复杂性:为什么在构造函数中进行计算? Consider this interface:考虑这个接口:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM