Reputation:
So, my assignment is to create a Ship class that has the attributes 'name' and 'fuel.' The name should have a default value of "Enterprise" and the fuel should have a default of 0. And I have to create a object with no parameters, each single parameter, and with both. The only one that's not working is the one with only the fuel and I'm not sure why.
Here's my code:
class Ship(object):
def __init__(self, name = "Enterprise", fuel = 0):
self.name = name
self.fuel = fuel
def status(self):
if self.fuel < 0:
self.fuel = 0
print self.name, "\nFuel:", self.fuel, "\n"
#main
ship1 = Ship()
ship1.status()
ship2 = Ship("Space Ship1")
ship2.status()
ship3 = Ship(10)
ship3.status()
ship4 = Ship("Space Ship2", 10)
ship4.status()
And here's what it's outputting:
Enterprise
Fuel: 0
Space Ship1
Fuel: 0
10
Fuel: 0
Space Ship2
Fuel: 10
The third one is printing the fuel as the name and defaulting the fuel to 0 which isn't right. How can I fix it?
Upvotes: 1
Views: 2326
Reputation: 32429
In ship3 = Ship(10)
the first parameter 10
is the name of the ship.
You might want to use ship3 = Ship(fuel=10)
.
Not directly related, but important nevertheless. Remember that if you use mutable objects as default arguments (which you don't in your example), those are evaluated once and not for each call.
Upvotes: 7