Python属性错误“Battery”对象没有属性“make” - 继承

时间:2018-03-13 20:22:34

标签: python oop inheritance attributes

我是一个Python菜鸟,并且在继承学习方面遇到了一些麻烦。我的代码抛出属性错误。

class Battery():
    """A simple attempt 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 battery size."""
        print("\n" + "This car has a " + str(self.battery_size) + 
        '-kWh battery.')

    def get_range(self):
        """Print a statement about the range based on the battery size."""
        if self.battery_size == 70:
            range = 240
        elif self.battery_size == 85:
            range = 270

    message = self.make + " can go approximately " + str(range)
    message += " miles on a full charge."
    print(message)


class ElectricCar(Car):
    """Represents aspects of a car, specific to electric vehicles."""

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

    def fill_gas_tank(self):
        """Electric cars don't have gas tanks."""
        print(self.make + "'s " + "don't need a gas tank.")

my_tesla = ElectricCar('tesla', 'p90d', '2016')
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()

我已经玩过编码和属性,但我似乎无法让它在没有错误的情况下运行。非常感谢任何指导。     Traceback(最近一次调用最后一次):       文件“C:\ Users \ n \ Downloads \ _ inheritance.py”,第184行,in         my_tesla.battery.get_range()       在get_range中输入文件“C:\ Users \ n \ Downloads \ _ inheritance.py”,第158行         message = self.make +“可以近似”+ str(范围)     AttributeError:'Battery'对象没有属性'make'

1 个答案:

答案 0 :(得分:0)

make未在电池中定义。您需要将make传递给Battery - 类:

class Battery():
    """A simple attempt to model a battery for an electric car."""
    def __init__(self, make, battery_size=70):
       """Initialize the battery's attributes."""
       self.make = make
       self.battery_size = battery_size
    ...

class ElectricCar(Car):
    """Represents aspects of a car, specific to electric vehicles."""

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

    def fill_gas_tank(self):
        """Electric cars don't have gas tanks."""
        print(self.make + "'s " + "don't need a gas tank.")