Reputation: 859
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.
Upvotes: 3
Views: 25690
Reputation: 1
If I understand your question, this will help you Assume we have class BankAccount: '''After Constructor, we have another method ''' def transfer(self,amount,object): #object is variable passed for referencing an object BankAccount.credit(self,amount) object.debit(amount)
call method bank1=BankAccount() bank1.transfer(2000,objectname)
Upvotes: 0
Reputation: 134841
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)
Upvotes: 1
Reputation: 74705
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)
Upvotes: 8