Things I’ve noticed and some other tips. Some of these can be applied to more than one place.
Class Rectangle
width = 0
height = 0
This is creating class variables, those would be the same for every instance created and would be accessible with syntax ClassName.variable
, in this case they aren’t required nor needed in any way.
Regarding lines:
def set_width(self, width):
self.width = width
self.side = width
Creation of not needed self.side
variable.
def get_area(self):
area = self.width * self.height
return area
If method is short, it doesn’t require any more complex operations and basically is just one variable assigned just to return it the next line, it’s often possible to skip the variable assignment as well. Resulting in return being just: return self.width * self.height
Regarding line:
r_pattern += ''.join('*')
join
method is obsolete here, it basically doesn’t do anything in this case.
Class Square
def __init__(self, side):
self.width = side
self.height = side
self.side = side
Part of this is repeating __init__
function from the parent class. Take a look at super()
function it allows for easy usage of original methods from the parent class (which might have been overridden in the child class). Using it you can simply use the __init__
method from Rectangle
class to set self.width
and self.height
instance variables. Consider also whether the explicit third variable for self.side
is needed or if it might be enough to just use self.width
and self.height
.
def set_side(self, side):
self.side = side
self.width = side
self.height = side
def set_width(self, side):
self.side = side
Notice that using set_width
method would change self.side
, while leaving self.width
and self.height
unchanged. Remember that other methods can be called from specific method too. This allows to make one method doing all necessary changes and then just call it from different methods that also should be able to perform these changes.