UML diagrams in python?

Viewed 338

I just got started learning about UML and I am currently trying to implement functionality for this diagram using python.

enter image description here

I have wrote the inheritance part, but I don't know yet how to deal with the association part of it. Could anyone give me some pointers on how to do this? Especially the circular reference.

My implementation so far:

class RailCar():
    def __init__(self, name):
        if len(name) >= 2:
            self.__name = name
            self.locomotive = None
        else:
            raise Exception("Name length of", type(self), " object must be at least 2 characters long.")

class PassengerCar(RailCar):
    def __init__(self, capacity):
        super().__init__(self, name)
        self.__capacity = capacity

class RestaurantCar(RailCar):
    def __init__(self, first):
        super().__init__(self, name)
        self.__first = first

class Locomotive():
    def __init__(self, railCar):
        self.railCar = railCar

rc01 = RailCar('01')
rc01.locomotive = "It works!!"
print(rc01.locomotive) 
1 Answers

Supposedly the self reference is a doppelganger of the private next attribute. It should rather be written with the role name next to the association like so:

enter image description here Anyhow, you would code it with self._next holding a reference to a RailCar instance. The getter/setter would then reference this private property.

class RailCar():
    def __init__(self, name):
        # as above 
        self._next = None


    def setNext(self, next):
        self._next = next
        # you might check if the instance is RailCar.

    @property
    def getNext(self):
        return self._next

P.S. The Locomotive-RailCar relation would be similar (with the same modeling issue). Just a self._first in Locomotive.

Related