Home > Software design >  Сan't decrement the values of sides
Сan't decrement the values of sides

Time:07-28

class Square:
    def __init__(self,s1,s2,s3,s4):
            self.side1 = s1
            self.side2 = s2
            self.side3 = s3
            self.side4 = s4

    def calculate_perimetr(self):
        return self.side1*self.side2*self.side3*self.side4
        
    def change_size(self,n):
        if n > 0 :
            self.side1  = n
            self.side2  = n
            self.side3  = n
            self.side4  = n
            print("Up")

        else:
            self.side1 -=n
            self.side2 -= n
            self.side3 -= n
            self.side4 -= n
            print("Down")


square1 = Square(10,10,10,10)
square1.change_size(-2)

print(square1.side1, square1.side2 ,square1.side3, square1.side4)

CodePudding user response:

If the class represents a square then all 4 sides are, by definition, equal. So let's assume that it's a rectangle. Then:

class Rectangle:
    def __init__(self, a, b, c, d):
        self.dimensions = [a, b, c, d]
    def perimiter(self):
        return sum(self.dimensions)
    def change_size(self, n):
        if n != 0:
            self.dimensions = [x n for x in self.dimensions]
            print('Up' if n > 0 else 'Down')

s = Rectangle(10, 10, 10, 10)
print(s.perimiter())
s.change_size(5)
print(s.perimiter())
s.change_size(-5)
print(s.perimiter())

Output:

40
Up
60
Down
40

CodePudding user response:

From looking over your codes, it seems like you want to decrement the value on passing -ve values. But when you do a subtraction on a negative value, it eventually sums up. So just change your logic like that.

    def change_size(self,n):
        self.side1  = n
        self.side2  = n
        self.side3  = n
        self.side4  = n
        if n > 0 :
            print("Up")
        else:
            print("Down")
  • Related