1 #什么是组合:其实就是在类定义中把需要的类放进去实例化就可以啦。
2 class A:
3 pass
4
5 class B:
6 pass
7
8 class C:
9 def __init__(self):
10 self.a = A()
11 self.b = B()
12
13
14 #C拥有了A和B,组合了A和B
15 #什么时候用组合呢,比如说,天上有一只鸟,水里有一条鱼。
16 #什么时候用继承呢,比如说,猫是动物,人也是动物
17 #-------------------------------------------------------------------
18
19 #类对象和实例对象:
20 #类对象在类定义完的时候,类定义就变成了类对象,可以直接通过"类名.属性"和"类名.方法()"引用相关的属性或者方法
21 #实例属性:是一个类的具体实例,将一个类具体化成实例,赋值给一个变量
22
23 #如果对象的属性和方法名相同时,对象属性会覆盖方法,避免方法是,属性用名词,方法用动词
24
25
26 #定义一个栈,后进先出特性的数据结构,方法:push(),pop(),top(),base()
27 class Stack:
28
29 def __init__(self, datas=[]):
30 self.count = 0 #用于计算目前有多少内容
31 self.data = []
32 for x in datas:
33 self.push(x)
34
35 def isEmpty(self):
36 return not bool(self.count)
37
38 def push(self,data):
39 self.count += 1
40 self.data.append(data)
41
42 def pop(self):
43 if self.isEmpty():
44 return -1
45 self.count -= 1
46 return self.data.pop()
47
48 def top(self):
49 if self.isEmpty():
50 return -1
51 return self.data[self.count-1]
52
53 def bottom(self):
54 if self.isEmpty():
55 return -1
56 return self.data[0]
57
58 a = Stack([1,2,3])
59 print(a.isEmpty())
60 print(a.pop())
61 print(a.isEmpty())
62 print(a.pop())
63 print(a.pop())
64 print(a.pop())
65 print(a.pop())
66