python 类之间的关系

匿名 (未验证) 提交于 2019-12-02 22:11:45

类与类之间的关系

1. 依赖关系

class Plant:     def __init__(self,zhonglei,xue,gongjili):         self.zhonglei = zhonglei         self.xue = xue         self.gongjili = gongjili      def da(self,js):         print("植物打僵尸")         js.xue -= self.gongjili         if js.xue <= 0:             print("僵尸死亡")         else:             print(f"僵尸掉血{self.gongjili},僵尸还剩{js.xue}血")  class Jiang:     def __init__(self,zhonglei,xue,gongjili):         self.zhonglei = zhonglei         self.xue = xue         self.gongjili = gongjili      def chi(self,zw):         print("僵尸咬植物")         zw.xue -= self.gongjili         if zw.xue <= 0:             print("植物死亡")         else:             print(f"植物掉血{self.gongjili},植物还剩{zw.xue}血") p = Plant("豌豆",1000,300) j = Jiang("路障",1800,200)  p.da(j) p.da(j) p.da(j) p.da(j) j.chi(p) j.chi(p) p.da(j) j.chi(p) j.chi(p) p.da(j)

2. 关联关系

class Boy:     def __init__(self, name,  girlFriend=None):         self.girlFriend = girlFriend  # 一个男孩有一个女朋友      def chi(self):         if self.girlFriend:             print(f"带着他的女朋友{self.girlFriend.name}去吃饭")         else:             print("单身狗, 吃什么吃? 滚去学习.")  class Girl:     def __init__(self, name):         self.name = name  b = Boy("宝宝") g = Girl("孙艺") b.chi()

  

  self.teach_list = [t1,t2,t3]

class School:      def __init__(self, name):         self.teach_list = [] # 这里要装多个老师         self.name = name      def zhaopin(self, teach):         self.teach_list.append(teach)      def shangke(self):         for t in self.teach_list:             t.work()  class Teacher:     def __init__(self, name):         self.name = name      def work(self):         print(f"{self.name}在上课")  s = School("蓝翔") t1 = Teacher("老师1") t2 = Teacher("老师2") t3 = Teacher("老师3") s.zhaopin(t1) s.zhaopin(t2) s.zhaopin(t3) s..shangke()

类中的关系: 依赖关系是最轻的. 最重的是继承关系. 关联关系是比较微妙的.

self到底是谁?

特殊成员:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!