python - Creating a Rectangle class -
i don't understand classes , great.
rectangle class should have following private data attributes:
__length
__width
the rectangle class should have __init__
method creates these attributes , initializes them 1. should have following methods:
set_length
– method assigns value__length
fieldset_width
– method assigns value__width
fieldget_length
– method returns value of__length
fieldget_width
– method returns value of__width
fieldget_area
– method returns area of rectangle__str__
– method returns 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 continue')
you've got few issues class
. see below comments
class rectangle: # init function def __init__(self): # members length , 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)
testing class
>>> = 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
as others have noted, setter's , getter's superfluous in python, member variables public. understand these methods required assignment, in future, know can save trouble , directly access members
>>> a.length # instead of getter 5 >>> a.length = 2 # instead of setter >>> a.length 2
Comments
Post a Comment