解决不同用途的相似物品的问题可以使用以下方法:
class Item:
def __init__(self, name, price):
self.name = name
self.price = price
def display_info(self):
print(f"Name: {self.name}, Price: {self.price}")
class Book(Item):
def __init__(self, name, price, author):
super().__init__(name, price)
self.author = author
def display_info(self):
super().display_info()
print(f"Author: {self.author}")
class Pen(Item):
def __init__(self, name, price, color):
super().__init__(name, price)
self.color = color
def display_info(self):
super().display_info()
print(f"Color: {self.color}")
book = Book("Python Programming", 29.99, "John Smith")
pen = Pen("Blue Pen", 1.99, "Blue")
book.display_info()
pen.display_info()
输出结果:
Name: Python Programming, Price: 29.99
Author: John Smith
Name: Blue Pen, Price: 1.99
Color: Blue
items = [
{"name": "Python Programming", "price": 29.99, "author": "John Smith"},
{"name": "Blue Pen", "price": 1.99, "color": "Blue"}
]
for item in items:
print(f"Name: {item['name']}, Price: {item['price']}")
if "author" in item:
print(f"Author: {item['author']}")
if "color" in item:
print(f"Color: {item['color']}")
输出结果:
Name: Python Programming, Price: 29.99
Author: John Smith
Name: Blue Pen, Price: 1.99
Color: Blue
以上是两种解决不同用途的相似物品的方法,分别使用面向对象编程和字典/列表存储数据的方式来实现。具体选择哪种方法取决于项目的需求和设计。
下一篇:不同右边框高度的问题