在以下代码中,在Battery类中,方法“ get_range”未打印我设置的消息。除了那一部分外,代码中的其他所有内容都会打印出来。 这是代码:
class Car(object):
"""A simple attempt to represnt a car"""
def __init__(self,make,model,year):
"""Initialize attributes to defiine a car"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + ' miles on it.')
def get_descriptive_name(self):
"""Return a neatly formatted descriptive name"""
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def update_odometer(self,mileage):
""" Set the odometer reading to the given value.
Reject the change if it attempts to roll the odometer back. """
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer")
# self.odometer_reading = mileage #### updating it through a method
def increment_odometer(self,miles):
self.odometer_reading += miles
class Battery():
"""A simple attempt to model a battery"""
def __init__(self,battery_zize = 70):
"""Initialize the batteries attributes"""
self.battery_size = battery_zize
def describe_battery(self):
"""Print statement describing the battery """
print("This car has a " + str(self.battery_size) + "-kwh battery")
def get_range(self):
"""Print a statement about the range this battery provides"""
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = "This car can go " + str(range)
message += " miles in a range"
print(message)
class ElectricCar(Car):
"""Represent aspects of a car, specific to electric vehicles."""
def __init__(self,make,model,year):
"""Initialize attributes of the parent class.
Then initialize attributes specific to the electric car"""
super().__init__(make,model,year)
self.battery = Battery()
my_tesla = ElectricCar('tesla','model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery() ##### find its battery attribute, and call the method describe_battery() that’s associated with the Battery instance stored in the attribute.
my_tesla.battery.get_range()
我没有收到任何错误消息,除了方法“ get_range”之外,所有内容都会打印出来。即使最后我确实叫它,这也是唯一一个不打印的东西。
答案 0 :(得分:2)
消息打印缩进,使得仅在self.battery_size == 85
时执行。