用面向对象为电脑估价,python代码
时间: 2024-05-05 13:21:16 浏览: 17
以下是一个简单的用面向对象为电脑估价的 Python 代码示例:
```python
class Computer:
def __init__(self, brand, model, year, condition, cpu, gpu, ram, storage):
self.brand = brand
self.model = model
self.year = year
self.condition = condition
self.cpu = cpu
self.gpu = gpu
self.ram = ram
self.storage = storage
def estimate_price(self):
base_price = 500 # 基础价格(美元)
# 品牌、型号和年份影响价格
if self.brand == 'Apple':
base_price += 500
elif self.brand == 'Dell':
base_price += 300
elif self.brand == 'HP':
base_price += 200
if self.year >= 2021:
base_price += 200
elif self.year >= 2019:
base_price += 100
# CPU、GPU、RAM和存储影响价格
if self.cpu == 'Intel Core i7':
base_price += 200
elif self.cpu == 'Intel Core i5':
base_price += 100
if self.gpu == 'NVIDIA GeForce GTX 1060':
base_price += 150
elif self.gpu == 'NVIDIA GeForce GTX 1050':
base_price += 100
base_price += self.ram * 10
base_price += self.storage * 0.1
# 状况影响价格
if self.condition == 'Like new':
base_price += 200
elif self.condition == 'Used':
base_price -= 100
return base_price
# 示例用法
my_computer = Computer('Apple', 'MacBook Pro', 2019, 'Used', 'Intel Core i7', 'NVIDIA GeForce GTX 1050', 16, 512)
print('Estimated price:', my_computer.estimate_price(), 'USD')
```
以上代码中,`Computer` 类表示一台电脑,具有品牌、型号、年份、状况、CPU、GPU、RAM和存储等属性,以及估价功能。`estimate_price` 方法根据电脑的属性计算出一个基础价格,并根据各个属性的影响因素进行调整,最终返回一个估价结果。
在示例中,我们创建了一台品牌为 Apple、型号为 MacBook Pro、年份为 2019 年、状况为 Used、CPU 为 Intel Core i7、GPU 为 NVIDIA GeForce GTX 1050、RAM 为 16GB、存储为 512GB 的电脑,并调用 `estimate_price` 方法进行估价,输出结果为 1620 美元。