本节主要内容:
1. 依赖关系
2. 关联关系, 组合关系, 聚合关系
3. 继承关系, self到底是什鬼?
4. 类中的特殊成员
⼀. 类与类之间的依赖关系 大千世界, 万物之间皆有规则和规律. 我们的类和对象是对大千世界中的所有事物进⾏归 类. 那事物之间存在着相对应的关系. 类与类之间也同样如此. 在面向对象的世界中. 类与类 中存在以下关系:
1. 依赖关系
2. 关联关系
3. 组合关系
4. 聚合关系
5. 继承关系
6. 实现关系
# class DaXiang:
# def open(self, bx): # 这里是依赖关系. 想执行这个动作. 必须传递一个bx
# print("大象高高兴兴走到了冰箱的面向前")
# bx.kai() # 传递来的对象执行kai()动作
# print("大象成功的打开了冰箱门")
#
# def zhuang(self):
# print("自己走进了冰箱")
#
# def close(self, bx):
# print("大象要关冰箱门了")
# bx.guan()
#
#
# class BingXiang:
# def kai(self):
# print("我是冰箱. 我会开门 ")
# def guan(self):
# print("我是冰箱. 我会关门 ")
#
# class DianFanGuo:
# def kai(self):
# print("我是电饭锅 我能开 ")
# def guan(self):
# print("我是电饭锅, 我能关 ")
#
# # bx1 = BingXiang()
# # bx2 = BingXiang()
# dx = DaXiang()
# dfg = DianFanGuo()
#
# dx.open(dfg)
# dx.zhuang()
# dx.close(dfg)
# def __init__(self, name, attack, hp):
# self.name = name
# self.attack = attack
# self.hp = hp
#
# def fight(self, js):
# js.hp -= self.attack
#
# class JiangShi:
# def __init__(self, name, hp, attack):
# self.name = name
# self.hp = hp
# self.attack = attack
#
# def chi(self, zhiwu):
# zhiwu.hp -= self.attack
#
# lvluo = ZhiWu("绿萝", 20, 10)
# js1 = JiangShi("僵尸一号", 100, 5)
# lvluo.fight(js1)
# lvluo.fight(js1)
# lvluo.fight(js1)
#
# js1.chi(lvluo)
# js1.chi(lvluo)
# js1.chi(lvluo)
# print(lvluo.hp)
# def __init__(self, name, girlFriend = None):
# self.name = name
# self.girlFriend = girlFriend # 关联关系
#
# def chi(self): # b
# if self.girlFriend:
# self.girlFriend.happy()
# print("%s和%s在吃饭" % (self.name, self.girlFriend.name))
# else:
# print("没女朋友吃什么吃")
#
# class Girl:
# def __init__(self, name):
# self.name = name
#
# def happy(self):
# print("有好吃的就开心")
#
#
# b = Boy("王明")
# g = Girl("肉丝")
# # b对象的girlFriend赋值 g
#
# b.girlFriend = g # 突然天降女朋友
# b.chi()
# b.girlFriend = None
# b.chi()
#
# class Teacher:
# def __init__(self, name, lst=None):
# self.name = name
# if lst == None: # 判断传递过来的参数是否是空
# self.lst = []
# else: # 传递过来的是一个列表
# self.lst = lst
#
# # 添加学生
# def tianjia(self, student):
# self.lst.append(student)
#
# def display(self):
# for s in self.lst: # s 是老师的学生
# print(s.name)
#
#
# class Student:
# def __init__(self, num, name, teacher=None):
# self.name = name
# self.num = num
# self.teacher = teacher
#
# t = Teacher("大张伟")
# s1 = Student(1, "郭德纲")
# s2 = Student(2, "岳云鹏")
# s3 = Student(3, "张鹤伦")
# s4 = Student(4, "朱云峰")
#
# t.tianjia(s1) # 把学生添加给老师
# t.tianjia(s2)
# t.tianjia(s4)
#
# t.display()