Here is the question; create a car class with the following data attributes
__year_model
__make
__speed
The class should have an __init__
method that accepts the car's year model and make as argument. The value should be assigned to the objects __year_model
and __make attributes
. It should assign 0 to the __speed
data attribute
It should also have the following method:
accelerate: accelerate should add 5 to the speed data attribute each time it is called.
brake: this method should subtract 5 from the speed
get_speed: this should display the current speed
Next, design a program that creates a Car object, and then calls the accelerate method five times. After each call to the accelerate method, get the current speed of the car and display it. Then call the brake method five times. After each call to the brake method, get the current speed of the car and display it.
class Car:
def __init__(self,year_model,make,speed):
self.year_mode = year_model
self.make = make
self.speed = 0
def accelerate(self,accelerate):
self.accelerate = accelerate
speed = 0
for x in range(5):
speed = speed + 5
print speed
def brake(self,brake):
self.brake = brake
speed = 0
for x in range(5):
brake = brake - 5
print brake
def get_speed(self):
return self.speed
test = Car(2006,'Honda',100)
I know test is the instance. Is it also the object? Thank you
Yes, test
is an object, ie an instance of a class is an object.
Your class needs some work. According to the spec, speed
is not supposed to be passed to __init__()
. Remove that and initialise self.__speed
to 0
in __init__()
.
accelerate()
and brake()
are not supposed to take arguments - each method should either increase the current speed by 5, or reduce the speed by 5. Therefore these methods do not require any arguments (other than self
).
So accelerate()
should be this:
def accelerate(self):
self.__speed += 5 # shorthand for self.speed = self.speed + 5
which simply increases the speed by 5 each time it is called. Note that self
is used so that the member __speed
is incremented, not some temporary local varible. You can do the same for brake()
.
Other than that, add the tests that your assignment specifies: call accelerate
5 times printing the speed after each call. Similarly for the brake
method. Does the output agree with what you would expect?
Test like this:
car = Car(2006,'Honda')
for i in range(5):
car.accelerate()
print(car.get_speed())
for i in range(5):
car.brake()
print(car.get_speed())
Oh, and name your members as per the spec: __speed
, not speed
etc.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.