Python类和对象

2024-09-24 02:16:53 发布

您现在位置:Python中文网/ 问答频道 /正文

运行程序时出错

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}$

Tags: oftheinpymainlinewidthlength
3条回答

您定义了一个Rectangle类,其初始值设定项方法需要两个参数:

class Rectangle:
    def __init__(self, length, width):

然而,您试图在不传递这些参数的情况下创建一个

^{pr2}$

输入长度和宽度:

my_rect = Rectangle(length, width)

下一个问题是area没有定义,您可能需要计算:

class Rectangle:
    def __init__(self, length, width):
        self.__length = length
        self.__width = width
        self.get_area(length, width)

关于设计注意事项:在Python中,通常不会使用这样的“private”变量;只需使用普通属性即可:

class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width

    @property
    def area(self):
        return self.length * self.width

并根据需要直接在实例上获取或设置这些属性:

print('The length is', my_rect.length)
print('The width is', my_rect.width)
print('The area is', my_rect.area)

以双下划线(__name)开头的属性旨在避免子类意外地重新定义它们;其目的是防止这些属性被删除,因为它们对当前类的内部工作至关重要。事实上,他们的名字被弄乱了,因此不太容易接近,这并不是说他们是私人的,只是更难联系到他们。不管你做什么,不要像在Java中那样把它们误认为私有名称。在

Rectangle的构造函数需要两个未设置的参数。在

参见:

class Rectangle:

    def __init__(self, length, width):

以及

^{pr2}$

您需要:

    my_rect = Rectangle(length, width)

仅供参考:

构造函数中的self参数是一个参数,它将被隐式地传递,这样您就不会传递它(至少在代码中实现它时是这样)。在

当您声明my_rect = Rectangle()时,它需要将length和{}传递给它,如Rectangle __init__方法所述。在

相关问题 更多 >