LU08.L01 - Einseitige Beziehung

house.py
class House:
    """
    A house of a certain type
 
    Attributes
    ----------
    type: String
        The type of the house ('Landhaus', 'Stadthaus', ...)
    """
 
    def __init__(self, name='Landhaus'):
        """
        Creates the object with the specified type
        """
        self._type = name
 
    @property
    def type(self):
        """ Returns the type of the house """
        return self._type
home_owner.py
class HomeOwner:
    """
    The owner of a house.
 
    Attributes
    ----------
    name: String
        The full name of the homeowner.
    my_house: House
        The house this person owns
    """
 
    def __init__(self, name, house):
        """
        Creates an object with the name and a reference to the house
 
        :param name: Full name of the homeowner.
        :param house: Reference to a house.
        """
        self._name = name
        self._my_house = house
 
    @property
    def name(self):
        """ Returns the full name. """
        return self._name
 
    def __str__(self):
        """
        Returns a string with information about the owner and his house.
        """
        return f'{self._name} besitzt ein {self._my_house.type}'
main.py
from home_owner import HomeOwner
from house import House
 
 
def main():
    house = House('Landhaus')
    owner = HomeOwner('Ron', house)  # Dem owner wird die Referenz zum Haus mitgegeben.
    print(owner)
 
 
if __name__ == '__main__':
    main()

René Probst, bearbeitet durch Marcel Suter

  • modul/m320_2024/learningunits/lu08/loesungen/einseitigebeziehung.txt
  • Zuletzt geändert: 2024/09/16 10:01
  • von msuter