码迷,mamicode.com
首页 > 其他好文 > 详细

类关系:继承和组合

时间:2018-09-21 19:51:17      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:技术分享   生成   组合关系   eve   nbsp   class   teacher   lap   def   

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

 

类关系:继承和组合

标签:技术分享   生成   组合关系   eve   nbsp   class   teacher   lap   def   

原文地址:https://www.cnblogs.com/andy9468/p/9687986.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!