我怎么能在我的类的方法中打印消息?

2024-06-23 18:31:21 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的代码中,在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”之外,所有内容都会打印出来。这是唯一一个没有打印的,尽管最后我确实打电话给它


Tags: thetonameselfgetmakemodeldef

热门问题