Product类似乎运行良好,但是我试图弄清楚如何使Inventory类将每种产品分成特定的类别。我觉得我已经接近了,但是每当我尝试打印清单时,它只会显示它在内存中的存储位置,而实际上并没有打印出任何内容。我在运行时收到的输出在底部。我希望它打印出实际的产品和数据,而不是打印存储在内存中的实例。
class Product:
def __init__(self, pid, price, quantity):
self.pid = pid
self.price = price
self.quantity = quantity
def __str__(self):
#Return the strinf representing the product
return "Product ID: {}\t Price: {}\t Quantity: {}\n".format(self.pid, self.price, self.quantity)
def get_id(self):
#returns id
return self.pid
def get_price(self):
#returns price
return self.price
def get_quantity(self):
#returns quantity
return self.quantity
def increase_quantity(self):
self.quantity += 1
def decrease_quantity(self):
self.quantity -= 1
def get_value(self):
value = self.quantity * self.price
return 'value is {}'.format(value)
product_1 = Product('fishing', 20, 10)
product_2 = Product('apparel', 35, 20)
class Inventory:
def __init__(self, products):
self.products = products
self.fishing_list = []
self.apparel_list = []
self.value = 0
def __repr__(self):
return "Inventory(products: {}, fishing_list: {}, apparel_list: {}, value: {})".format(self.products, self.fishing_list, self.apparel_list, self.value)
def add_fishing(self):
for product in self.products:
if product.get_id() == 'fishing':
self.fishing_list.append(product)
return '{} is in the fishing section'.format(self.fishing_list)
def add_apparel(self):
for product in self.products:
if product.get_id() == 'apparel':
self.apparel_list.append(product)
return '{} is in the apparel section'.format(self.apparel_list)
inventory_1 = Inventory([product_1, product_2])
inventory_1.add_fishing()
print(inventory_1)
输出=库存(产品:[<< strong>主要。产品实例位于0x10dbc8248>,主要。产品实例位于0x10dbc8290>),fishing_list:[<< strong>主要。产品实例位于0x10dbc8248>],服装列表:[],值:0)
答案 0 :(得分:0)
您需要指定应如何打印类Inventory
的对象。
为此,您需要在类中至少实现以下功能之一。
__repr__
__str__
此答案有帮助,您应该使用两者中的哪一个:https://stackoverflow.com/a/2626364/8411228
一个实现可能看起来像这样:
class Inventory:
# your code ...
def __repr__(self):
return str(self.products) + str(self.fishing_list) + str(self.apparel_list) + str(self.value)
# or even better with formatting
def __repr__(self):
return f"Inventory(products: {self.products}, fishing_list: {self.fishing_list}, apparel_list: {self.apparel_list}, value: {self.value})
请注意,我在第二个示例f strings中使用了格式化输出字符串的方式。