Получена следующая ошибка, но я вижу, что есть созданный мной атрибут, который я установил равным созданному мной классу.
Traceback (most recent call last):
File "C:/Users/Rachel/Desktop/Practice/ch9.py", line 125, in <module>
new_tesla.battery.describe_battery()
AttributeError: 'ElectricCar' object has no attribute 'battery'
Это код.
class Battery():
"""Model batter for a electric car"""
def __init__(self,battery_size = 70):
self.battery_size = battery_size
def describe_battery(self):
"""print statement about battery size"""
print("This car has a " + str(self.battery_size) + "-kWh battery.")
class ElectricCar(Car):
"""Represent a electric car"""
def __init___(self,make,model,year):
"""
Initialize attributes of the parent class,
then initialize attributes specific to electric car
"""
super().__init__(make,model,year)
self.battery = Battery()
new_tesla = ElectricCar('Big tesla',"model Z",'2020')
new_tesla.battery.describe_battery()
Изменить: добавлен код для класса Car
class Car():
def __init__(self,make,model,year):
"""Initializes attributed to describe a car."""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 # default value
# takes the parameters and stores them as attributes that will be associated with instances
# made from this class
def descriptive_name(self):
"""Describes car"""
print("Make is " + self.make.title() + ", model is " + self.model.title() + " from the year " + self.year)
def read_odometer(self):
"""Reads odometer"""
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
"""
Set odometer to different value
Reject change if odometer is rolled back
"""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("cannot roll back odometer.")
def fill_gas(self):
print('Glug glug....')
def increment_odometer(self,miles):
"""Add the given amount to the odometer reading."""
if miles > 0:
self.odometer_reading += miles
else:
pass
Я почти уверен, что делаю это правильно. Я скопировал код прямо из cra sh course python. Я вижу, что сделал класс атрибутом .. понятия не имею, что не так.