增加一个布尔属性,用于跟踪商品是否已被购买。
示例代码:
class Item: def init(self, name, price): self.name = name self.price = price self.purchased = False # 添加一个布尔属性,默认值为False
def purchase(self):
self.purchased = True
print(f"{self.name}已购买")
item1 = Item("商品1",10) print(item1.purchased) # 输出False item1.purchase() print(item1.purchased) # 输出True