gpt4 book ai didi

Python初学者: Setting a variable in a subclass

转载 作者:行者123 更新时间:2023-11-30 22:18:16 25 4
gpt4 key购买 nike

正在学习 Python 初学者类(class),目前正在上课。例如,本书使用汽车/电动汽车的描述来解释类和子类等。

代码如下:

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()

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

在电池的init中,电池容量默认设置为 70 kWh。

如何调用 Battery() 将车辆的电池容量设置为 85 kWh?

最佳答案

只需给它一个值:

self.battery = Battery(85)

仅当没有值传递到函数中时才使用默认值,否则使用传递的参数。

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

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

关于Python初学者: Setting a variable in a subclass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49418737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com