【发布时间】: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