2013-12-22 30 views
4

我剛剛開始學習python,並對如何傳遞一個對象的實例作爲函數的參數感到困惑,下面是我爲實踐製作的一小段代碼,其基本思想是有一個車庫,這個車庫不包含汽車,您可以將汽車添加到車庫並查看其詳細信息。如何在python中的函數中將對象的實例作爲參數傳遞?

class Garage: 
    cars = [] 

    def add_car(self, car): 
     cars.append(car) 

class Car: 
    car_name, car_price, car_colour, car_miles, car_owners = "", "", "", "", "" 

    def add_new_car(self, garage, name, price, colour, miles, owners): 
     car_name = name 
     car_price = price 
     car_colour = colour 
     car_miles = miles 
     car_owners = owners 

     garage.add_car(self) 

def main(argv=None):  
    your_garage = Garage() 

    while True: 
     print "Your garage contains %d cars!" % len(your_garage.cars) 
     print "1) Add a new car\n2) View your car's\n0) Leave the garage" 
     user_input = raw_input("Please pick an option: ") 

     if user_input == "1": 
      add_car(your_garage) 
     elif user_input == "2": 
      view_cars(your_garage) 
     elif user_input == "0": 
      quit() 

def add_car(garage): 
    name = raw_input("Name: ") 
    price = raw_input("Price: ") 
    colour = raw_input("Colour: ") 
    miles = raw_input("Miles: ") 
    owners = raw_input("Owners: ") 

    car = Car() 
    car.add_new_car(garage, name, price, colour, miles, owners) 

def view_cars(garage): 
    for x in xrange(len(garage.cars)): 
     print garage.cars[x].car_name 
     print garage.cars[x].car_price 
     print garage.cars[x].car_colour 
     print garage.cars[x].car_miles 
     print garage.cars[x].car_owners 

if __name__ == "__main__": 
    main() 

我的代碼可能是非常錯誤的或有可能是一個簡單的方法來做到這一點,我的路我想象它會是我創造了汽車的新實例將被傳遞到add_car()功能在車庫,以便它可以被添加到汽車列表。我怎樣才能做到這一點?

+0

我相信你可以通過傳遞方法(this)在Java中做到這一點,然後將'this'作爲對象的實例傳遞。 – nickmcblain

回答

1

也許這個簡單的例子會指出你在正確的方向。當前代碼中的一個主要問題是,您應該在__init__方法(或其他一些在實例上運行的方法)中設置實例級別的屬性(例如,汽車的顏色或車庫的汽車庫存),而不是在班級一級。

class Garage: 
    def __init__(self): 
     self.cars = []   # Initialize instance attribute here. 

    def add_car(self, car): 
     self.cars.append(car) 

class Car: 
    def __init__(self, color): 
     self.color = color  # Ditto. 

    def __repr__(self): 
     return "Car(color={})".format(self.color) 

def main(): 
    g = Garage() 
    for c in 'red green blue'.split(): 
     c = Car(c) 
     g.add_car(c)  # Pass the car to the garage's add_car method. 
    print g.cars   # [Car(color=red), Car(color=green), Car(color=blue)] 

if __name__ == "__main__": 
    main() 
相關問題