views:

67

answers:

2

I have a module including definitions for two different classes in Python. How do I use objects of one class as an argument of the other? Say, I have class definitions for Driver and Car, and tuen want to have a Driver object as an argument for a Car object.

+1  A: 

Create an instance of a Driver object and pass it to the Car's constructor.

e.g.,

>>> d = Driver()
>>> c = Car(d)

or just

>>> c = Car(Driver())

[edit]

So you're trying to use an instance of a driver as you define a class? I'm still not sure I understand what it is you're trying to do but it sounds like some kind of decorator perhaps.

def OwnedCar(driver):
    class Car(object):
        owner = driver
        #...
    return Car

steve = Driver()
SteveCar = OwnedCar(steve)
Jeff M
My question was a bit unclear, what I mean is how to handle object argument in the class definition: class Car: def __init__(self, driverA) driverA.foo() driverA.bar()Does this work, or do I have to define the type of Driver in the class definitions?
rize
@rize In python you try it and see if it works. to answer your question, no you do not need to define the type of the argument `DriverA`. If `DriverA.foo` and `DriverA.bar` exist, then there will be no error. You could pass it a `Pilot` as long as `Pilot.foo` and `Pilot.bar` exist and do what you want.
aaronasterling
A: 

Update: The OP is trying to pass an object instance at class definition time (or so I think after seeing his comment). The answer below is not applicable.

Is this what you are trying to achieve?

class Car:
    def __init__(self, driver):
        self.driver = driver

class Driver:
    pass

driver = Driver()
car = Car(driver)
Manoj Govindan
Yes, that's exactly what I'm trying to do: pass an object instance at class definition time
rize
Ah. Can you tell me how you are using that object instance in the class definition? Your comment above seems to use it in the class *constructor*, which doesn't make much sense. Posting some code would help.
Manoj Govindan