Python_level_2/1lession/1.2_Car.py

63 lines
2.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

class Car:
def __init__(self, spec: dict):
# Валидации в данном случае подходят только для атрибутов с числовым форматом.
# Как сделать изящнее без кучи if-ов при условии что атрибут может быть строкой (например, марка, модель и тд)?
for item in spec:
if type(spec.get(item)) not in {int, float}:
raise TypeError('Параметр %s должен быть числом' % item)
if spec.get(item) < 0:
raise ValueError('Параметр %s не может быть отрицательным' % item)
if spec.get('gas') > spec.get('capacity'):
raise ValueError('Количество топлива в баке не может быть больше объема бака')
self.gas_l = spec.get('gas')
self.capacity_l = spec.get('capacity')
self.l_per_km = spec.get('consumption')
self.odometer = spec.get('odometer')
def fill(self, value):
if type(value) not in {int, float}:
raise TypeError('Объем заправляемого топлива должен быть числом')
if value < 0:
raise ValueError('Объем заправляемого топлива не может быть отрицательным')
result = self.gas_l + value
if result > self.capacity_l:
self.gas_l = self.capacity_l
print("Осталось лишнее топливо: %s литров" % (result - self.capacity_l))
else:
self.gas_l = result
def ride(self, distance):
remain = distance
while remain > 0:
self.odometer += 1
self.gas_l = round(self.gas_l - self.l_per_km, 2)
remain -= 1
if self.gas_l == 0:
break
result = distance - remain
print("Проехали %s километров" % result)
def main():
c1_spec = {
"gas": 30,
"capacity": 40,
"consumption": 0.1,
"odometer": 10000
}
c1 = Car(c1_spec)
print("Исходные данные:", c1.gas_l, c1.capacity_l, c1.l_per_km, c1.odometer)
c1.fill(5)
print("Показатели после заправки:", c1.gas_l, c1.capacity_l, c1.l_per_km, c1.odometer)
print()
c1.ride(100)
print("Показатели после поездки:", c1.gas_l, c1.capacity_l, c1.l_per_km, c1.odometer)
if __name__ == '__main__':
main()