Python类和对象错误
我在运行程序时出错Python类和对象错误,python,python-3.x,Python,Python 3.x,我在运行程序时出错 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\rec
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'
您定义了一个矩形类,其初始值设定项方法需要两个参数:
class Rectangle:
def __init__(self, length, width):
my_rect = Rectangle()
但您尝试创建一个,而不传入这些参数:
class Rectangle:
def __init__(self, length, width):
my_rect = Rectangle()
改为传入长度和宽度:
my_rect = Rectangle(length, width)
下一个问题是未定义面积,您可能需要计算:
class Rectangle:
def __init__(self, length, width):
self.__length = length
self.__width = width
self.get_area(length, width)
在设计说明上:在Python中,通常不使用像这样的“私有”变量;只需使用普通属性即可:
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)
以双下划线名称开头的属性旨在避免子类意外地重新定义它们;其目的是保护这些属性不被破坏,因为它们对于当前类的内部工作至关重要。事实上,他们的名字被弄乱了,因此不太容易接近,但这并没有真正使他们变得隐私,只是更难接近。无论您做什么,都不要像在Java中那样将它们误认为私有名称。当您声明my_rect=Rectangle时,它需要长度和宽度才能传递给它,正如Rectangle方法中所述。Rectangle的构造函数需要两个您没有设置的参数 见: 及 你需要:
my_rect = Rectangle(length, width)
仅供参考:
构造函数中的self参数是一个隐式传递的参数,因此您不需要传递它,至少不需要在代码中实现它。在矩形类中定义u_init__;的方法要求您使用长度和宽度调用它:
def __init__(self, length, width):
改变
my_rect = Rectangle()
my_rect.set_length(length)
my_rect.set_width(width)
到
嗨,我是python编程的初学者。这是我的第一个对象和类程序在访问类文件时遇到问题
my_rect = Rectangle()
my_rect.set_length(length)
my_rect.set_width(width)
my_rect = Rectangle(length, width)