在python中,如何将对象实例作为参数传递给函数?

在python中,如何将对象实例作为参数传递给函数?,python,oop,Python,Oop,我刚刚开始学习python,对如何将对象的实例作为函数的参数传递感到困惑,下面是我为实践而编写的一些代码,基本思想是有一个车库,这个车库不包含汽车,您可以将汽车添加到车库并查看其详细信息 class Garage: cars = [] def add_car(self, car): cars.append(car) class Car: car_name, car_price, car_colour, car_miles, car_owners = "

我刚刚开始学习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()函数中,以便可以将其添加到汽车列表中。我怎样才能做到这一点呢?

也许这个简化的例子将为您指明正确的方向。当前代码中的一个主要问题是,您应该在
\uuuuu init\uuuuu
方法(或在其他一些对实例进行操作的方法中)内部设置实例级属性(例如,汽车的颜色或车库的汽车库存),而不是在类级

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()

我相信您可以在Java中通过传递方法(this)来实现这一点,然后传递对象的实例“this”。