我真的不太了解课程,任何帮助都会很棒。
\n\n矩形类应具有以下私有数据属性:
\n\n__length __widthRectangle 类应该有一个 __init__方法来创建这些属性并将它们初始化为 1。它还应该有以下方法:
set_length__length\xe2\x80\x93 该方法为字段赋值
set_width__width\xe2\x80\x93 该方法为字段赋值
get_length__length\xe2\x80\x93 该方法返回字段的值
get_width__width\xe2\x80\x93 该方法返回字段的值
get_area\xe2\x80\x93 该方法返回 Rectangle 的面积
__str__\xe2\x80\x93 该方法返回对象\xe2\x80\x99s 状态
class Rectangle:\n\n def __init__(self):\n self.set_length = 1\n self.set_width = 1\n self.get_length = 1\n self.get_width = 1\n self.get_area = 1\n\ndef get_area(self):\n self.get_area = self.get_width * self.get_length\n return self.get_area\n\n\ndef main():\n\n my_rect = Rectangle()\n\n my_rect.set_length(4)\n my_rect.set_width(2)\n\n print('The length is',my_rect.get_length())\n print('The width is', my_rect.get_width())\n\n print('The area is',my_rect.get_area())\n print(my_rect)\n\n input('press enter to continue')\nRun Code Online (Sandbox Code Playgroud)\n
Python 不限制对私有数据属性的访问,因此您很少需要像限制性更强的语言那样编写“getters”和“setters”(我们都是同意的成年人)。
除非它是供内部使用的(您将来可能会更改的实现细节),否则您只需将属性公开给世界即可 - 所以更惯用的矩形将是这样的:
class Rectangle(object):
def __init__(self, width=1, height=1):
self.width = width
self.height = height
@property
def area(self):
return self.width * self.height
Run Code Online (Sandbox Code Playgroud)
然后:
>>> r = Rectangle(5, 10)
>>> r.area
50
>>> r.width = 100
>>> r.area
1000
Run Code Online (Sandbox Code Playgroud)
当然,您可以使用 getter 和 setter 编写 Rectancle 类,但只有当您想要验证或转换输入时才这样做 - 那么您可能想了解有关 @property装饰器的更多信息。