面向對象【五】類的組合

python之類的組合

 

類的組合

學校與課程沒有共同點,課程與老師沒有共同點,可是學校與課程有關聯,課程與老師有關聯;學校、課程、老師是三個徹底不一樣的類;課程是屬於學校的,老師是教課程的,此時咱們就用到類的組合來關聯,學校-課程,課程-老師;html

複製代碼
class School:
    """
    學校類
    """
    def __init__(self,name,address):
        self.name = name
        self.address = address
class Course:
    """
    課程類
    """
    def __init__(self,name,price,period,school):
        self.name = name
        self.price = price
        self.period = period
        self.school = school
class Teacher:
    """
    老師類
    """
    def __init__(self,name,gender,age,course):
        self.name = name
        self.gender = gender
        self.age = age
        self.course = course
#學校實例化
x1 = School("oldboy","北京校區")
x2 = School("oldboy","天津校區")
x3 = School("oldboy","南京校區")
#課程實例化
k1 = Course("python",19880,"6個月",x1) #課程與學校關聯
k2 = Course("linux",17880,"4個月",x2)
k3 = Course("go",20000,"8個月",x3)
#教師實例化
j1 = Teacher("alex","male",34,k2) #教師與課程關聯
j2 = Teacher("武sir","male",30,k1)
j3 = Teacher("林海峯","male",35,k3)
print(k1.__dict__)
print(k1.school.name)
print(j1.__dict__)
print(j1.course.name)
複製代碼
class School:
    """
    學校類
    """
    def __init__(self,name,address):
        self.name = name
        self.address = address
class Course:
    """
    課程類
    """
    def __init__(self,name,price,period,school):
        self.name = name
        self.price = price
        self.period = period
        self.school = school
class Teacher:
    """
    老師類
    """
    def __init__(self,name,gender,age,course):
        self.name = name
        self.gender = gender
        self.age = age
        self.course = course
#學校實例化
x1 = School("oldboy","北京校區")
x2 = School("oldboy","天津校區")
x3 = School("oldboy","南京校區")
#課程實例化
k1 = Course("python",19880,"6個月",x1) #課程與學校關聯
k2 = Course("linux",17880,"4個月",x2)
k3 = Course("go",20000,"8個月",x3)
#教師實例化
j1 = Teacher("alex","male",34,k2) #教師與課程關聯
j2 = Teacher("武sir","male",30,k1)
j3 = Teacher("林海峯","male",35,k3)
print(k1.__dict__)
print(k1.school.name)
print(j1.__dict__)
print(j1.course.name)

msg = """
oldboy 北京校區
oldboy 天津校區
oldboy 南京校區
"""
res = """
python
linux
go
"""
while True:
    print(msg)
    menu = {
        "1":x1,
        "2":x2,
        "3":x3,
    }
    choice = input("選擇學校>>>:")
    school_boj = menu[choice]
    name = input("課程名稱>>>:")
    price = input("課程價錢>>>:")
    period = input("課程週期>>>:")
    new_course = Course(name,price,period,school_boj)
    print("課程【%s】屬於【%s】學校"%(new_course.name,new_course.school.name))
    print(res)
    inner = {
        "1":k1,
        "2":k2,
        "3":k3,

    }
    choice1 = input("選擇課程>>>:")
    course_boj = inner[choice1]
    name = input("老師名稱>>>:")
    gender = input("老師性別>>>:")
    age = input("老師年齡>>>:")
    new_teacher = Teacher(name,gender,age,course_boj)
    print("老師【%s】教的是【%s】"%(new_teacher.name,new_teacher.course.name))

選課系統
選課系統
相關文章
相關標籤/搜索