创建一个Rectangle类 [英] Creating a Rectangle class
问题描述
我真的不太了解类,任何帮助都会很棒。
I really don't understand classes very much and any help would be great.
Rectangle类应具有以下私有数据属性:
Rectangle class should have the following private data attributes:
-
__ length
-
__ width
__length
__width
Rectangle类应具有 __ init __
方法,创建这些属性并将其初始化为1。它还应具有以下方法:
The Rectangle class should have an __init__
method that creates these attributes and initializes them to 1. It should also have the following methods:
-
set_length
–此方法为__ length
字段
set_width
–此方法为 __ width
字段分配一个值
set_width
– this method assigns a value to the __width
field
get_length
–此方法返回 __ length
字段的值
get_length
– this method returns the value of the __length
field
get_width
–此方法返回 __ width
字段的值
get_width
– this method returns the value of the __width
field
get_area
–此方法返回Rectangle的面积
get_area
– this method returns the area of Rectangle
__ str __
–此方法返回对象的状态
__str__
– this method returns the object’s state
class Rectangle:
def __init__(self):
self.set_length = 1
self.set_width = 1
self.get_length = 1
self.get_width = 1
self.get_area = 1
def get_area(self):
self.get_area = self.get_width * self.get_length
return self.get_area
def main():
my_rect = Rectangle()
my_rect.set_length(4)
my_rect.set_width(2)
print('The length is',my_rect.get_length())
print('The width is', my_rect.get_width())
print('The area is',my_rect.get_area())
print(my_rect)
input('press enter to continue')
推荐答案
您的类
遇到了一些问题。参见下面的注释
You've got a few issues with your class
. See the below comments
class Rectangle:
# Init function
def __init__(self):
# The only members are length and width
self.length = 1
self.width = 1
# Setters
def set_width(self, width):
self.width = width
def set_length(self, length):
self.length = length
# Getters
def get_width(self):
return self.width
def get_length(self):
return self.length
def get_area(self):
return self.length * self.width
# String representation
def __str__(self):
return 'length = {}, width = {}'.format(self.length, self.width)
测试班级
>>> a = Rectangle()
>>> a.set_width(3)
>>> a.set_length(5)
>>> a.get_width()
3
>>> a.get_length()
5
>>> a.get_area()
15
>>> print(a)
length = 5, width = 3
和getter在Python中是多余的,因为所有成员变量都是公共的。我知道这些方法是您分配工作所必需的,但是在将来,您知道您可以省去麻烦,直接访问成员即可
As others have noted, setter's and getter's are superfluous in Python, as all member variables are public. I understand that these methods are required for your assignment, but in the future, know that you can save yourself the trouble and just directly access the members
>>> a.length # Instead of the getter
5
>>> a.length = 2 # Instead of the setter
>>> a.length
2
这篇关于创建一个Rectangle类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!