如何同时关联两个Class集合?蟒蛇

时间:2018-12-11 16:58:07

标签: python class set

因此,我想创建一个允许卡车和驾驶员相互关联的代码。 如果驾驶员隶属于卡车,那么他现在正在驾驶它。当卡车隶属于驾驶员时,他现在也正在驾驶它。

所以我想更改两类的隶属关系:驾驶员和卡车。 但是,当我使用 setTruck()函数将卡车设置为驾驶员时,该驾​​驶员的卡车现在隶属于该卡车,但是该卡车却不隶属于该驾驶员...

当我将卡车设置为驾驶员时,我想同时将驾驶员设置为卡车。

这是我的代码,我希望有人能理解我的意图, 预先谢谢你们。

  class Driver:
    def __init__(self, name, lastname, truck = None):
        self.name = name
        self.lastname = lastname
        self.truck = truck

    def __str__(self):
        return 'Name : {}, Lastname : {}\n'.format(self.name, self.lastname)

    def setTruck(self, truck):
        self.truck = truck
        truck.setDriver(self.name)
    def getTruck(self):
        return 'Truck : {}'.format(self.truck)

class Vehicule:
    def __init__(self, tv, plaque, driver = None):
        self.plaque = plaque
        self.tv = tv
        self.driver = driver

    def __str__(self):
        return 'Plaque : {}, Type : {}\n'.format(self.plaque,self.tv)

    def setDriver(self, driver):
        self.driver = driver

    def getDriver(self):
        return 'Driver : {}'.format(self.driver)

# Create a Driver and a Truck
truck = Vehicule('PL','AA-111-AA')
johndoe = Driver("John",'Doe')
# Print their attribut
print(johndoe)
print(truck)
# Print their affilations
print(johndoe.getTruck())
print(truck.getDriver())
# Set the truck to our driver
johndoe.setTruck(truck)
# Print their affilations
print(johndoe.getTruck())
print(truck.getDriver())

0 个答案:

没有答案