Python中组合的使用方法,是直接在类的定义中把需要组合的类实例化放进去就可以了.
// ==========乌龟类==========
class Turtle:
def __init__(self, x):
self.num = x
// ==========鱼类==========
class Fish:
def __init__(self, x):
self.num = x
// ==========水池类==========
class Pool:
def __init__(self, x, y):
self.turtle = Turtle(x) // 组合乌龟类进来
self.fish = Fish(y) // 组合鱼类进来
def print_num(self):
print("水池里总共有乌龟 %d 只,小鱼 %d 条!" % (self.turtle.num, self.fish.num))
>>> pool = Pool(1, 10)
>>> pool.print_num()
// ==========Python模拟栈==========
class Stack:
def __init__(self, start=[]):
self.stack = []
for x in start:
self.push(x)
def isEmpty(self):
return not self.stack
def push(self, obj):
self.stack.append(obj)
def pop(self):
if not self.stack:
print('警告:栈为空!')
else:
return self.stack.pop()
def top(self):
if not self.stack:
print('警告:栈为空!')
else:
return self.stack[-1]
def bottom(self):
if not self.stack:
print('警告:栈为空!')
else:
return self.stack[0]