class Square():
def __init__(self, side):
self.side = side
def getArea(self):
return side*side
def getAreaOfAllInstances(self):
{need to write this method}
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)`
答案 0 :(得分:1)
您可以使用类变量:
class Square():
squares = []
def __init__(self, side):
self.side = side
self.squares.append(self)
def getArea(self):
return self.side * self.side
def getAreaOfAllInstances(self):
return sum(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)
但这不是一个干净的解决方案。我宁愿创建另一个类来跟踪Square。像这样:
class Square:
def __init__(self, side):
self.side = side
def getArea(self):
return self.side * self.side
class SquareContainer:
def __init__(self):
self.squares = []
def create_square(self, side):
square = Square(side)
self.squares.append(square)
return square
def getAreaOfAllInstances(self):
return sum(s.getArea() for s in self.squares)
sc = SquareContainer()
s1 = sc.create_square(2)
s2 = sc.create_square(3)
print(sc.getAreaOfAllInstances())
答案 1 :(得分:0)
确定可以:
class Square():
_all_instances = []
def __init__(self, side):
self.side = side
self._all_instances.append(self)
def getArea(self):
return side*side
@classmethod
def getAreaOfAllInstances(cls):
return sum(inst.getArea() for inst in cls._all_instances)
但是请注意,这意味着除非您清空Square
属性,否则将永远不会收集Square._all_instances
。
答案 2 :(得分:0)
您可以使用类方法来实现这一目标。
<div id='nav'>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
</div>
输出:
class Square(object):
instances_list = [] # Property of the class
def __init__(self, side):
self.trackInstances(self)
self.side = side
def getArea(self):
return self.side**2
@classmethod
def trackInstances(cls, self):
self.instances_list.append(self)
@classmethod
def getAreaOfAllInstances(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()
请注意,只有square of all instances: 13
被执行,它给出了所有实例的区域。