我正在构建一个knapsack
将(另一个类)列表Items
作为参数的类。每个物品都有一个重量和一个价值,一个背包应该有一个总重量(所有的总和item.weights
)和总价值(所有的总和item.values
)。
我想要完成的knapsack.total_weight
是knapsack.total_value
在knapsack.items.append(new_item)
.
到目前为止,我已经尝试过装饰items
,total_weight
和total_value
with @property
,但它似乎不起作用。关于如何正确使用属性装饰器的任何想法,或者我应该查看不同的实现?
class Item:
def __init__(self,name:str,weight:int,value:int):
self.name = name
self.weight = weight
self.value = value
def __str__(self):
return f'{self.name}: {self.weight}kg ({self.value})'
class Knapsack:
def __init__(self,items=[],max_weight=250,score=None,weight=None):
self.max_weight = max_weight
self._items = items
self._score = score
self._weight = weight
@property
def items(self):
return self._items
@items.setter
def items(self,new_item):
self._items += [new_item]
self._score = self._items
self._weight = self._items
@property
def score(self):
return self._score
@score.setter
def score(self,items):
total_score = 0
for item in items:
total_score += item.value
self._score = total_score
@property
def weight(self):
return self._weight
@weight.setter
def weight(self,items):
total_weight = 0
for item in items:
total_weight += item.weight
self._weight = total_weight
def __str__(self):
out = [item.name for item in self.items]
return f'{"".join(out)}\t{self.score}'