A school has several school classes:

"Has an" association between School and SchoolClass

"Has an" association between School and SchoolClass

Notes:

  • School needs a property of type List (or array) for holding more than one school class.
  • School has a method addSchoolClass() for adding further school classes.

This type of "Has an" association can be realized in Python as follows:

School.py

Contains two Class definitions:

# School.py

class School:                           
    def __init__(self,schoolClasses):
        self.__schoolClasses = schoolClasses
        
    def getSchoolClasses(self):
        return self.__schoolClasses

    def addSchoolClass(self, schoolClass):        # adds a school class 
        self.__schoolClasses.append(schoolClass)
        
    
class SchoolClass:
    def __init__(self,name):
        self.__name = name
        
    def getName(self):
        return self.__name

testSchool.py

Demonstrates the use of the above defined classes:

# testSchool.py

from School import *                       # Import all from School.py 

school = School([])                        # Creation of object school with empty list 
schoolClass = SchoolClass("c1")

school.addSchoolClass(schoolClass)         # adding of schoolclasses
school.addSchoolClass(SchoolClass("c2"))

schoolClasses = school.getSchoolClasses()  # get list
for sc in schoolClasses:                   # For loop iterates over list
    print(sc.getName())

In Python the For loop is used for iterating over a list.


UML object diagram

UML object diagram

Note: In this example the second object of class SchoolClass has no object name, because it was directly created while parameter passing. This kind of ownership is called composition. This object is owned exclusively in contrast to the first object schoolclass, which could be owned additionally by other objects (aggregation).

Last modified: Monday, 21 October 2019, 10:40 AM