运行程序时出错
Enter the length of the rectangle: 4
Enter the width of the rectangle: 2
Traceback (most recent call last):
File "C:\Users\Shourav\Desktop\rectangle_startfile.py", line 50, in <module>
main()
File "C:\Users\Shourav\Desktop\rectangle_startfile.py", line 34, in main
my_rect = Rectangle()
TypeError: __init__() missing 2 required positional arguments: 'length' and 'width'
代码:
^{pr2}$
您定义了一个
Rectangle
类,其初始值设定项方法需要两个参数:然而,您试图在不传递这些参数的情况下创建一个:
^{pr2}$输入长度和宽度:
下一个问题是
area
没有定义,您可能需要计算:关于设计注意事项:在Python中,通常不会使用这样的“private”变量;只需使用普通属性即可:
并根据需要直接在实例上获取或设置这些属性:
以双下划线(
__name
)开头的属性旨在避免子类意外地重新定义它们;其目的是防止这些属性被删除,因为它们对当前类的内部工作至关重要。事实上,他们的名字被弄乱了,因此不太容易接近,这并不是说他们是私人的,只是更难联系到他们。不管你做什么,不要像在Java中那样把它们误认为私有名称。在Rectangle的构造函数需要两个未设置的参数。在
参见:
以及
^{pr2}$您需要:
仅供参考:
构造函数中的self参数是一个参数,它将被隐式地传递,这样您就不会传递它(至少在代码中实现它时是这样)。在
当您声明}传递给它,如
my_rect = Rectangle()
时,它需要将length
和{Rectangle __init__
方法所述。在相关问题 更多 >
编程相关推荐