Python---TypeError:Battery.get_range() 缺少 1 个必需的位置参数:'self'

问题描述 投票:0回答:1

主程序-

"""A class that can be used to represent a car."""

class Car:
"""A simple attempt to represent a car."""

    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year 
        self.odometer_reading = 0
    
    def get_descriptive_name(self):
        """Return a neatly formative descriptive name."""
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()
    
    def read_odometer(self):
        """Print a statement showing the car's mileage."""
        print(f"This car has {self.odometer_reading} miles on it.")
    
    def update_odometer(self, mileage):
        """
        Set the odometer reading to a given value.
        Reject the change if it attempt to roll the odometer back.
        """
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
    
        else:
            print("You can't roll back an odometer!")
    
    def increment_odometer(self, miles)  :
        """Add the given amount to the odometer."""      
        self.odometer_reading += miles

class Battery:
"""A simple atytempt to model a battery for an electric car"""

    def __init__(self, battery_size=70):
        """Initialize the battery's attributes"""
        self.battery_size = battery_size
        
    def describe_battery(self):
        """Print a statement describing the size of the battery."""    
        print(f"This car has a {self.battery_size}-kWh battery.")
    
    def get_range(self):
        """Print a statement about the range thgis battery provides."""
        if self.battery_size == 75:
            range = 260
        elif self.battery_size == 100:
            range = 315
    
        print(f"This can go about {range} miles on a full charge.")

class ElectricCar(Car):
"""Models aspects of car, specific to electric vehicle."""

    def __init__(self, make, model, year):
        """
        Initialize attributes specific to an electric car.
        Then initialize attribute specific to an electric car.
        """
        super().__init__(make, model, year)
        self.battery = Battery()

secong program-

from car import ElectricCar

my_tesla = ElectricCar('tesla', 'model s', 2019)

print(my_tesla.get_descriptive_name())

my_tesla.battery.describe_battery()

my_tesla.battery.get_range()

输出

2019 Tesla Model S
This car has a 75-kWh battery.
This car can go about 260 miles on a full charge.
python
1个回答
0
投票

在电池类

def __init__(self, battery_size=70)
中,您初始化了battery_size = 70。

要获得所需的输出

This car can go about 260 miles on a full charge.
,请设置battery_size = 75。所以它应该如下所示:

    def __init__(self, battery_size=75):
        """Initialize the battery's attributes"""
        self.battery_size = battery_size
© www.soinside.com 2019 - 2024. All rights reserved.