1

Add methods in another method of a same class

I created 2 method (first, last) and a third one (sum); I want the sum of returned value of first and last and then stored in sum; then I want to display the returned value of the sum.

P.S. I am practicing class and object. This problem can be solved using very basic syntax but I want to learn the class and objects. I am telling this cause, you may think that why am I doing this when there are easier way to do that. ;)

Thanks

class Total:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def first(self):
        if self.x < 15:
            return self.x * self.y
        else:
            return self.x - self.y

    def last(self):
        if self.x < 100:
            return self.x + 5
        else:
            return self.x - 6

    def sum(self):
        pass
        # I need help here
        # add returned value of first() and last()


p = Total(25, 5)
p.sum()

Submitted July 17th 2021 by Admin

Answers
0

You can return the first() and last() methods accumulated sum from the sum() method like:

class Total: def __init__(self, x, y): self.x = x self.y = y def first(self): if self.x < 15: return self.x * self.y else: return self.x - self.y def last(self): if self.x < 100: return self.x + 5 else: return self.x - 6 def sum(self): return self.first() + self.last() p = Total(25, 5)
print(p.sum())

Output:

50

Admin | 1 week ago



Relevant Questions