python摸爬滚打之day17----类与类之间的关系

1、类与类之间的联系

 1.1  依赖关系

   类A中使用了类B, 类B作为参数传进类A的方法中被使用. 这种关系中类与类之间的联系是最轻的. 

 1 class Elephant:
 2 
 3     def open(self,ele):             # ele 接收的是一个BingXiang的对象
 4         print("我是大象,我会开门")         
 5         ele.kai()
 6 
 7     def jinqu(self):
 8         print("我是大象,我会自己进封闭容器")
 9 
10     def close(self,ele):
11         print("我是大象,我会关门")
12         ele.guan()
13 
14 
15 class BingXiang:
16 
17     def kai(self):
18         print("我是冰箱,我会替别人开门")
19 
20     def guan(self):
21         print("我是冰箱,我会替别人关门")
22 
23 
24 class DianFanBao:
25 
26     def kai(self):
27         print("我是电饭煲,我会替别人开门")
28 
29     def guan(self):
30         print("我是电饭煲,我会替别人关门")
31 
32 
33 bx = BingXiang()
34 dfb = DianFanBao()
35 e = Elephant()
36 e.open(bx)
37 e.jinqu()
38 e.close(dfb)
依赖关系

 1.2 关联关系(组合关系,聚合关系)

   三种关系写法是一样的, 但意义是不一样的.

  关联关系: 类A和类B是互相关联的, 类A中使用了类B, 类B成为类A中的属性或成员. 关系程度要比依赖关系强点. 

 1 class Teacher:
 2 
 3     def __init__(self,name,lst=None):
 4         self.name = name
 5         if lst == None:
 6             self.lst = []
 7         else:
 8             self.lst = lst
 9 
10     def add_sd(self,obj):
11         self.lst.append(obj)       # 将这几个学生对象添加进self.lst这个老师类的字段中,成为该属性的一部分.
12 
13 
14 class Student:
15 
16     def __init__(self,name,numb,score):
17         self.name = name
18         self.numb = numb
19         self.score = score
20 
21 s1 = Student("王大锤",1001,95)
22 s2 = Student("李二炮",1003,90)
23 s3 = Student("马老五",1004,88)
24 t = Teacher("张老师",[Student("二壮",1010,99)])
25 t.add_sd(s1)
26 t.add_sd(s2)
27 t.add_sd(s3)
28 for i in t.lst:
29     print(i.name)
关联关系

 1.3  继承关系

   见后续. 

2、特殊成员方法

  __new__()

  __init__()

  __call__()

  __str__()

  __int__()

  __repr__()

  __getitem__()

  __setitem__()

  __delitem__()

  __enter__()

  __exit__()

  __add__()

  __len__()

  __iter__()

  __hash__()

  __dict__()

猜你喜欢

转载自www.cnblogs.com/bk9527/p/9931526.html