Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass instance of an object as an argument in a function in python?

Tags:

python

oop

I am just starting to learn python and am getting confused about how to pass an instance of an object as an argument for a function, below is a little bit of code I made for practice and the basic idea is that there is one garage, this garage contains no cars, and you can add cars to the garage and view their details.

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

My code might be very wrong or there might be an easy way to do this, I the way I pictured it was going to be that the new instance of car I created would be passed into the add_car() function in Garage so that it can be added to the list of cars. How can I do this?

like image 640
nickmcblain Avatar asked Dec 22 '13 02:12

nickmcblain


People also ask

Can you pass any type of object as an argument to a function Python?

A function can take multiple arguments, these arguments can be objects, variables(of same or different data types) and functions. Python functions are first class objects.

How instances are passed as parameters in Python?

Consider a simple class Foo where each instance keeps an integer value with a function bar that returns the value with 1 added to it. When externally using this class, it is normal to write Foo(3). bar() . In this instance, Foo(3) is an instance of Foo and is passed as the self parameter in bar() .


1 Answers

Maybe this simplified example will point you in the right direction. One of the main problems in your current code is that you should be setting instance-level attributes (for example, a car's color or a garage's inventory of cars) inside the __init__ method (or in some other method operating on instances), not up at the class level.

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()
like image 58
FMc Avatar answered Sep 28 '22 03:09

FMc