面向对象格式输出商品的基本信息代码
这是一个面向对象的商品类,包含商品的基本信息和输出格式。
class Goods:
def __init__(self, name, price, quantity):
self.name = name
self.price = price
self.quantity = quantity
def __str__(self):
return f"{self.name}: ${self.price} ({self.quantity} available)"
def show_item_info(self):
print(f"Item Name: {self.name}")
print(f"Price: ${self.price}")
print(f"Quantity Available: {self.quantity}")
使用示例:
apple = Goods("Apple", 0.5, 100)
print(apple) # 输出:Apple: $0.5 (100 available)
apple.show_item_info()
# 输出:
# Item Name: Apple
# Price: $0.5
# Quantity Available: 100
可以看到,通过实例化一个Goods对象,可以输出商品的基本信息,并且通过show_item_info方法,可以以特定格式输出商品的详细信息
原文地址: https://www.cveoy.top/t/topic/hq0l 著作权归作者所有。请勿转载和采集!