首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python属性错误"Battery“对象没有"make”属性-继承

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

Stack Overflow用户
提问于 2018-03-14 04:22:34
回答 1查看 567关注 0票数 0

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

代码语言:javascript
复制
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()

我已经尝试了编码和属性,但我似乎不能让它运行没有一个错误。任何指导都是非常感谢的。回溯(最近一次调用):文件"C:\Users\n\Downloads\inheritance.py",第184行,在my_tesla.battery.get_range()文件"C:\Users\n\Downloads\inheritance.py",第158行,在get_range消息= self.make +“can go object”+str(范围) AttributeError:'Battery‘对象没有属性'make’

EN

回答 1

Stack Overflow用户

发布于 2018-03-14 04:34:31

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

代码语言:javascript
复制
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.")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49265245

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档