Python: object as an argument of another object
22,729
Solution 1
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)
Solution 2
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)
Author by
rize
Updated on May 06, 2020Comments
-
rize almost 4 years
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.