以下是一個雙向關聯的例子,在下方的類別圖中,1門課程登錄了0個或多個學生,一個學生也選修了0門或多門課程,不管從Course或Student類別,都可以連結到與其相關的對方物件。
class Course():
'''
課程類別
屬性:
(1)名稱
(2)學分數
(3)修課學生
'''
def __init__(self, name, credit):
self.name = name
self.credit = credit
self.__students = [] #有哪些學生選修
@property
def name(self): return self.__name
@name.setter
def name(self, name): self.__name = name
@property
def credit(self): return self.__credit
@credit.setter
def credit(self, credit): self.__credit = credit
def add(self, student):
self.__students.append(student)
def list(self):
r = []
for s in self.__students:
r.append(s)
return r
class Student():
'''
學生類別
屬性:
(1)學號
(2)姓名
(3)選修科目
'''
def __init__(self, id, name):
self.id = id
self.name = name
self.__courses = [] #選修哪些科目
@property
def id(self): return self.__id
@id.setter
def id(self, id): self.__id = id
@property
def name(self): return self.__name
@name.setter
def name(self, name): self.__name = name
def add(self, course):
self.__courses.append(course) #將課程加給自己
course.add(self) #將自己記錄在課程中
def list(self):
r = []
for c in self.__courses:
r.append(c)
return r
def printStuInfo(student):
for c in student.list():
print(f'{student.id} {student.name} 選修了{c.name}')
def printCouInfo(course):
for s in course.list():
print(f'{course.name} {course.credit}學分, 有{s.id}{s.name}選修')
#----------------------
# 建立課程物件
#----------------------
c1 = Course('國文', 2)
c2 = Course('英文', 3)
c3 = Course('數學', 2.5)
#----------------------
# 建立學生物件
#----------------------
s1 = Student('1001', '王小明')
s2 = Student('1002', '陳小華')
s3 = Student('1003', '張小文')
#----------------------
# 學生選修課程
#----------------------
s1.add(c1)
s1.add(c3)
s2.add(c3)
s3.add(c1)
s3.add(c2)
s3.add(c3)
#----------------------
# 印出學生選修資訊
#----------------------
printStuInfo(s1)
printStuInfo(s2)
printStuInfo(s3)
#----------------------
# 印出課程選修資訊
#----------------------
printCouInfo(c1)
printCouInfo(c2)
printCouInfo(c3)
1001 王小明 選修了國文
1001 王小明 選修了數學
1002 陳小華 選修了數學
1003 張小文 選修了國文
1003 張小文 選修了英文
1003 張小文 選修了數學
國文 2學分, 有1001王小明選修
國文 2學分, 有1003張小文選修
英文 3學分, 有1003張小文選修
數學 2.5學分, 有1001王小明選修
數學 2.5學分, 有1002陳小華選修
數學 2.5學分, 有1003張小文選修