LU08.L02 - Zweiseitige Beziehung

customer.py
class Customer:
    """
    The customer who makes a reservation for an event
 
    Attributes
    ----------
    name: String
        the full name of the customer
    reservation: Reservation
        the reservation object for this customer
    """
 
    def __init__(self, name, reservation):
        """ creates the customer """
        self._name = name
        self._reservation = reservation
        reservation.customer = self
 
    def __str__(self):
        """ returns as String representation of this customer """
        return f'{self.name} hat eine Reservation für den Anlass {self._reservation.event}'
 
    @property
    def name(self):
        """ gets the name """
        return self._name
 
    @property
    def reservation(self):
        """ gets the reservation """
        return self._reservation
reservation.py
class Reservation:
    """
    A reservation for an event
 
    Attributes
    ----------
    event: String
        the name of the event
    number: String
        the reservation number
    customer: Customer
        the customer this reservation belongs to
    """
 
    def __init__(self, number, name):
        """ Creates the reservation """
        self._event = name
        self._number = number
        self._the_customer = None
 
    def __str__(self):
        """ Returns a String representation of this reservation """
 
        if self.customer is not None:
            return f'Reservation {self.number} {self.event} für Kunde {self.customer.name}'
        else:
            return f'{self.event} ist kein Kunde zugeordnet'
 
    @property
    def event(self):
        """ gets the event """
        return self._event
 
    @property
    def number(self):
        """ gets the number """
        return self._number
 
    @property
    def customer(self):
        """ gets the customer """
        return self._the_customer
 
    @customer.setter
    def customer(self, customer):
        """ sets the customer """
        self._the_customer = customer
main.py
from customer import Customer
from reservation import Reservation
 
 
def main():
    """ creates some objects and calls some methods """
 
    reservation = Reservation('123', 'ESAF')
    customer = Customer('Julian', reservation)
    print(customer)
    print(reservation)
 
 
if __name__ == '__main__':
    main()

René Probst, bearbeitet durch Marcel Suter

  • modul/m320_2024/learningunits/lu08/loesungen/zweiseitigebeziehung.txt
  • Zuletzt geändert: 2024/09/16 09:59
  • von msuter