1. 程式人生 > 實用技巧 >python基礎-面向物件(五)類的組合

python基礎-面向物件(五)類的組合

類的組合:一個物件的屬性值是另一個類的例項物件。

當類之間明顯不同,但又有關聯的時候用組合

示例1:人的頭,腳

a.在__init__裡實例化

class Head:
    print('head')


class Person:
    def __init__(self, name):
        self.name = name
        self.foot = Foot() #例項化
        self.hand = Hand()
        self.head = Head()


person1 = Person('alex')

b.在外部例項化

class
Foot(): def __init__(self, name): self.foot = name class Hand: def __init__(self, name): self.hand = name class Person: def __init__(self, name, foot, hand): self.name = name self.foot = foot self.hand = hand foot1 = Foot('旺財的') person1 = Person('
alex', foot1, 'hand') # 把例項作為引數傳入 print(person1.foot.foot)

示例2:學校和課程的關係

class School:
    def __init__(self, name, addr):
        self.name = name
        self.addr = addr


class Course:
    def __init__(self, name, teacher, school):
        self.name = name
        self.teacher = teacher
        self.school 
= school s1 = School('清華', '北京') s2 = School('北大', '雲南') course1 = Course('python', '愛華', s1) print('我要去%s的%s上%s的%s' % (course1.school.addr, course1.school.name, course1.teacher, course1.name))

做成與使用者互動形式的。

class School:
    def __init__(self, name, addr):
        self.name = name
        self.addr = addr


class Course:
    def __init__(self, name, teacher, school):
        self.name = name
        self.teacher = teacher
        self.school = school


s1 = School('清華', '北京')
s2 = School('北大', '雲南')
s3 = School('川大', '四川')

while True:
    msg1 = '''
        1 清華 北京
        2 北大 雲南
        3 川大 四川'''
    print(msg1)
    menu = {
        '1': s1,
        '2': s2,
        '3': s3
    }
    choice_school = input('請輸入選擇的學校:')
    msg2 = '''
    1 python
    2 linux
    3 java'''
    print(msg2)
    menu2 = {
        '1': 'python',
        '2': 'linux',
        '3': 'java'
    }
    choice_course = input('請輸入選擇的課程:')
    course = Course(menu2[choice_course], '李華', menu[choice_school])
    print('你選擇的是%s的%s課' % (menu[choice_school].name, menu2[choice_course]))
    break