Python
-------------------------
### Description
In this exercise, you will add to your `Battery` class
a method to drain the battery.
### Class Name
`Battery`
### Method
`drain()`
### Parameters
* `self` : the `Battery` object to use
* `milliamps` : a number, the amount of charge to remove from the
battery.
### Action
Removes `milliamps` from the charge of the object. If the
new charge is less than 0, then set the charge to 0.
Only do this action of `milliamps` is positive, and
the `Battery` isn't already at 0 charge.
### Return Value
`True` if a change occurred, `False` otherwise.
class Battery:
def __init__(self, capacity):
self.capacity = capacity
def getCapacity(self):
return self.capacity
def getCharge(self):
return self.capacity
def drain(self, milliamps):
self.milliamps = milliamps
if self.capacity < 0:
return False
else:
return True
I have completed your class, there was one variable missing, charge , which I added. I have also added some statements to test
class Battery:
def __init__(self, capacity, charge):
self.capacity = capacity
self.charge = charge
def getCapacity(self):
return self.capacity
def getCharge(self):
return self.charge
def drain(self, milliamps):
if milliamps > 0 and self.charge != 0:
self.charge = self.charge - milliamps
if self.charge < 0:
self.charge = 0
return True
else:
return False
b = Battery(20, 18)
print("Current Charge:", b.charge)
b.drain(10)
print("After draining 10 milliamps, Charge:", b.charge)
Get Answers For Free
Most questions answered within 1 hours.