1. 程式人生 > >類關系:繼承和組合

類關系:繼承和組合

() 繼承 logs tel __init__ www. 關系圖 elf ini

1、繼承

技術分享圖片

2、組合

技術分享圖片

3、繼承和組合

在jichengandzuhe.py中

class People:
    def __init__(self, name, age, sex, year, mon, day):
        self.name = name
        self.age = age
        self.sex = sex
        self.birth = Date(year, mon, day)

    def walking(self):
        print(‘%s is walking ‘ % self.name)

    def talking(self):
        print(‘%s is talking ‘ % self.name)


class Date:
    def __init__(self, year, mon, day):
        self.year = year
        self.mon = mon
        self.day = day

    def tell_birth(self):
        print(‘出生於<%s>年 <%s>月 <%s>日‘ % (self.year, self.mon, self.day))


class Teacher(People):
    def __init__(self, name, age, sex, level, salary, year, mon, day):
        # People.__init__(self, name, age, sex, year, mon, day)
        super(Teacher,self).__init__(name, age, sex, year, mon, day)
        self.level = level
        self.salary = salary

    def teaching(self):
        People.talking(self)
        print(‘%s is teaching‘ % self.name)


class Student(People):
    def __init__(self, name, age, sex, year, mon, day, group):
        People.__init__(self, name, age, sex, year, mon, day)
        self.group = group

    def studying(self):
        People.talking(self)
        print(‘%s is studying‘ % self.name)


t1 = Teacher(‘egon‘, 18, "男", "初級", 3000, 1990, 9, 10)
print(t1.name, t1.age)
t1.walking()
t1.talking()
s1 = Student(‘xiaobai‘, 22, "女", 2008, 1, 20, "一組")
print(s1.name, s1.age)
s1.talking()
s1.walking()

  

類關系圖:

技術分享圖片

birth是People類的一個實例屬性,

birth的值為Date類的一個實例化對象,

故,Date類是People類的組成部分,屬於組合關系。

延伸:類圖生成工具:https://www.cnblogs.com/andy9468/p/8353613.html

類關系:繼承和組合