Spaceship objects
I'm trying to make a program which creates a spaceship and I'm using the status() method to display the ship's name and fuel values. However, it doesn't seem to be working. I think I may have messed something up with the status() method. I'm also trying to make it so that I can change the fuel values, but I don't want to create a new method to do so. I think I've taken a horrible wrong turn somewhere in there. Help please!
class Ship(object):
def __init__(self, name="Enterprise", fuel=0):
self.name=name
self.fuel=fuel
print "The spaceship", name, "has arrived!"
def status():
print "Name: ", self.name
print "Fuel level: ", self.fuel
status=staticmethod(status)
def main():
ship1=Ship(raw_input("What would you like to name this ship?"))
fuel_level=raw_input("How much fuel does this ship have?")
if fuel_level<0:
self.fuel=0
else:
self.fuel(fuel_level)
ship2=Ship(raw_input("What would you like to name this ship?"))
fuel_level2=raw_input("How much fuel does this开发者_如何学Go ship have?")
if fuel_level2<0:
self.fuel=0
else:
self.fuel(fuel_level2)
ship3=Ship(raw_input("What would you like to name this ship?"))
fuel_level3=raw_input("How much fuel does this ship have?")
if fuel_level3<0:
self.fuel=0
else:
self.fuel(fuel_level3)
Ship.status()
main()
raw_input("Press enter to exit.")
Each ship has its own fuel, so static isn't the way to go. If you don't want the parameter to look like a method, consider a property. It encapsulates the value-checking of the fuel as well.
class Ship(object):
def __init__(self, name="Enterprise", fuel=0):
self.name = name
self._fuel = fuel
print "The spaceship", name, "has arrived!"
def status(self):
print "Name: ", self.name
print "Fuel level: ", self.fuel
@property
def fuel(self):
return self._fuel
@fuel.setter
def fuel(self,level):
if level < 0:
self._fuel = 0
else:
self._fuel = level
In main(), consider loops to initialize the ships and display status instead of repeating code, and use ship.fuel instead of self.fuel. self is only valid in methods of the class.
def main():
ships = []
for n in range(4):
ship = Ship(raw_input("What would you like to name this ship?"))
ship.fuel = int(raw_input("How much fuel does this ship have?"))
ships.append(ship)
for ship in ships:
ship.status()
main()
raw_input("Press enter to exit.")
In your status
method self
is not defined, because you made it a static method. It makes more sense to make it non-static, since every ship has its individual name. So just say
def status(self):
print "Name: ", self.name
print "Fuel level: ", self.fuel
and later call
ship1.status()
ship2.status()
ship3.status()
精彩评论