Skip to content Skip to sidebar Skip to footer

Return The Sum Of Values Returned By Another Method Of All The Instances Of That Class?

class Square(): def __init__(self, side): self.side = side def getArea(self): return side*side def getAreaOfAllInstances(self): {need to write

Solution 1:

You can use class variable:

classSquare():
    squares = []
    def__init__(self, side):
        self.side = side
        self.squares.append(self)

    defgetArea(self):
        return self.side * self.side

    defgetAreaOfAllInstances(self):
        returnsum(s.getArea() for s in self.squares)

s1 = Square(2)
s2 = Square(3)

print(s1.getAreaOfAllInstances()) #===> This should print 13 (2*2 + 3*3)print(s2.getAreaOfAllInstances()) # ===> This should print 13 (2*2 + 3*3)

But that's not a clean solution. I'd rather create another class, to keep track of Squares. Like this:

classSquare:
    def__init__(self, side):
        self.side = side

    defgetArea(self):
        return self.side * self.side


classSquareContainer:
    def__init__(self):
        self.squares = []

    defcreate_square(self, side):
        square = Square(side)
        self.squares.append(square)
        return square

    defgetAreaOfAllInstances(self):
        returnsum(s.getArea() for s in self.squares)

sc = SquareContainer()
s1 = sc.create_square(2)
s2 = sc.create_square(3)

print(sc.getAreaOfAllInstances())

Solution 2:

Sure you can:

classSquare():

    _all_instances = []

    def__init__(self, side):
        self.side = side
        self._all_instances.append(self)

    defgetArea(self):
        return side*side

    @classmethoddefgetAreaOfAllInstances(cls):
        return sum(inst.getArea() for inst in cls._all_instances)

Note however that this means that Squares will never be gargabe collected, except if you empty the Square._all_instances attribute.

Solution 3:

You can use classmethods to achieve this.

classSquare(object):
    instances_list = []  # Property of the classdef__init__(self, side):
        self.trackInstances(self)
        self.side = side

    defgetArea(self):
        return self.side**2    @classmethoddeftrackInstances(cls, self):
        self.instances_list.append(self)

    @classmethoddefgetAreaOfAllInstances(cls):
        areaSum = sum(map(lambda i: i.getArea(), cls.instances_list))
        print('square of all instances: {}'.format(areaSum))

s1 = Square(2)
s2 = Square(3)

s2.getAreaOfAllInstances()

Output:

square of all instances: 13

Note that only s2.getAreaOfAllInstances is executed, and it gives the areas of all instances.

Post a Comment for "Return The Sum Of Values Returned By Another Method Of All The Instances Of That Class?"