您如何检查用户是否至少传递了一个参数?
How do you check if the user passes at least one of the arguments?
有时一个对象可以由不同类型的参数构造。例如,可以通过提供半径或周长来定义圆形对象。如何编写 __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
是否正确?
我什至不知道这里的半径和周长是可选参数还是必需参数,因为其中至少有一个是必需的。有没有人可以赐教一下?
如果提供两个参数,我只会优先考虑其中一个。它会是这样的:
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")
假设,您想要回答标题问题:
您的代码看起来不错,但您可以使用 **kwargs
参数而不是列出所有可能的候选者,可以轻松检查其中是否包含某些内容,而无需深入了解细节。
对于一般方法:
我猜你对功能的分解增加了复杂性:为什么要在构造函数中进行计算?考虑这个界面:
c = Circle()
c.setRadius(4.5) # alternatively: c.setCircumference(13.7)
print(c.getArea())
有时一个对象可以由不同类型的参数构造。例如,可以通过提供半径或周长来定义圆形对象。如何编写 __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
是否正确?
我什至不知道这里的半径和周长是可选参数还是必需参数,因为其中至少有一个是必需的。有没有人可以赐教一下?
如果提供两个参数,我只会优先考虑其中一个。它会是这样的:
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")
假设,您想要回答标题问题:
您的代码看起来不错,但您可以使用 **kwargs
参数而不是列出所有可能的候选者,可以轻松检查其中是否包含某些内容,而无需深入了解细节。
对于一般方法:
我猜你对功能的分解增加了复杂性:为什么要在构造函数中进行计算?考虑这个界面:
c = Circle()
c.setRadius(4.5) # alternatively: c.setCircumference(13.7)
print(c.getArea())