Search code examples
pythonpython-3.xclasscomposition

Is it possible to have two way composition in python?


First off I am very sorry if this is the wrong way to ask this question so please don't rip me. What I am trying to do is something very similar to the following.

class Driver:
    def __init__(self):
        self.kind = "Driver"
    def class_of_driver(self):
        if self.model == 'corvette':
            print('fast')
class Car:
    def __init__(self, brand, model, cost, color):
        self.brand = brand
        self.model = model
        self.cost = cost
        self.color = color
        self.drivers = Driver()

I want to be able to create the object like this:

corvette = Car('chevy','corvette','200','red')

Then ulitmately be able to do something like:

corvette.class_of_driver

or

corvette.class_of_driver()

and get the return of fast in this scenario. I have been messing with this for an hour and so and becoming stuck. I know I can pass self into itself like:

self.drivers = Driver(self)

But of course if the object changes in the future it will not reflect this change.

Any advice would be greatly appreciated and let me say thank you in advance.


Solution

  • Sure you can. It is fairly common for two objects to hold references to each other. Here is one way to do it:

    class Driver:
        def __init__(self, car):
            self.kind = "Driver"
            self.car = car
        def class_of_driver(self):
            if self.car.model == 'corvette':
                print('fast')
    class Car:
        def __init__(self, brand, model, cost, color):
            self.brand = brand
            self.model = model
            self.cost = cost
            self.color = color
            self.driver = Driver(self)
    
        def class_of_driver(self):
            return self.driver.class_of_driver()
    
    
    corvette = Car('chevy','corvette','200','red')
    
    corvette.class_of_driver()