太空飞船的对象

时间:2010-03-23 14:16:56

标签: python object static-methods

我正在尝试创建一个创建宇宙飞船的程序,我正在使用status()方法来显示船名和燃料值。但是,它似乎没有起作用。我想我可能用status()方法搞砸了。我也试图这样做,以便我可以改变燃料值,但我不想创建一个新的方法来做到这一点。我想我在某处发生了一次可怕的错误转弯。求救!

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 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.")

2 个答案:

答案 0 :(得分:4)

在您的status方法self中未定义,因为您将其设为静态方法。因为每艘船都有自己的名字,所以把它变成非静态更有意义。所以只说

def status(self):
    print "Name: ", self.name
    print "Fuel level: ", self.fuel

以后再打电话

ship1.status()
ship2.status()
ship3.status()

答案 1 :(得分:4)

每艘船都有自己的燃料,所以静电是不可能的。如果您不希望参数看起来像方法,请考虑属性。它还包含了燃料的价值检查。

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

在main()中,考虑循环来初始化船只并显示状态而不是重复代码,并使用ship.fuel而不是self.fuel。 self仅在类的方法中有效。

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.")