Python constructors with default values? -
so, assignment create ship class has attributes 'name' , 'fuel.' name should have default value of "enterprise" , fuel should have default of 0. , have create object no parameters, each single parameter, , both. 1 that's not working 1 fuel , i'm not sure why.
here's 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 it's outputting:
enterprise fuel: 0 space ship1 fuel: 0 10 fuel: 0 space ship2 fuel: 10
the third 1 printing fuel name , defaulting fuel 0 isn't right. how can fix it?
in ship3 = ship(10)
first parameter 10
name of ship.
you might want use ship3 = ship(fuel=10)
.
not directly related, important nevertheless. remember if use mutable objects default arguments (which don't in example), evaluated once , not each call.
Comments
Post a Comment