Python组合的实例用法

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]

    原文作者:不忘初元
    原文地址: https://blog.csdn.net/hllsmart/article/details/51347984
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞