首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python :在子类中设置变量

Python :在子类中设置变量
EN

Stack Overflow用户
提问于 2018-03-22 00:38:35
回答 1查看 86关注 0票数 1

通过初级课程学习Python,目前正在上课。作为一个例子,这本书是用汽车/电动汽车的描述来解释类和子类等等。

以下是代码:

代码语言:javascript
复制
class Car():
    ''' A simple attempt to represent a car ''' 

    def __init__(self, make, model, year):
        ''' Initialize attributes to describe a car '''
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def car_description(self):
        ''' Return a neatly formatted descriptive name '''
        long_name = str(self.year) + ' ' + self.make + ' ' + self.model
        return long_name.title()

class ElectricCar(Car):
    # When we put (Car) in the class definition, a child class is created with the attributes of Car.
    ''' Represents aspects of a car, specific to electric vehicles. ''' 

    def __init__(self, make, model, year):
        ''' Initalize attributes of the parent class. '''
        super().__init__(make,model,year)
        self.battery = Battery()

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("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 approximately " + str(range)
        message += " miles on a full charge."
        print(message)

my_tesla = ElectricCar('tesla','model s', 2016)
print(my_tesla.car_description())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()

在类电池()中,方法get_range显示两个可能的电池大小(70和85),以及它们各自的范围。

在电池的init中,电池的大小默认设置为70 kWh。

我如何调用电池()将电池大小设置为85 kWh的车辆?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-22 00:43:05

只要给它一个价值:

代码语言:javascript
复制
self.battery = Battery(85)

只有在没有传递给函数的值时才使用默认值,否则将使用传递的参数。

正如@jasonharper所建议的,您可以在ElectricCar__init__()方法中添加一个参数,指定电池大小:

代码语言:javascript
复制
def __init__(self, make, model, year, batterySize):
    ''' Initalize attributes of the parent class. '''
    super().__init__(make,model,year)
    self.battery = Battery(batterySize)
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49418737

复制
相关文章

相似问题

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