• 类与对象实例


    #coding:utf8
    from random import randint
    import time
    
    class tiger:
        name='Tiger'
    
        def __init__(self,weight=200):
            self.weight=weight
    
        def __repr__(self):
            return "tiger()"
    
        def roar(self):
            print("wow")
            self.weight-=5
            print "weight-5"
    
        def food(self,food):
            if food=='meat':
                self.weight+=10
                print "weight+10"
            else:
                self.weight-=10
                print "weight+10"
    
    class sheep:
    
        name='Sheep'
    
        def __init__(self,weight=100):
            self.weight=weight
    
        def __repr__(self):
            return "sheep()"
    
        def roar(self):
            print('mie')
            self.weight-=5
            print "weight-5"
    
        def food(self,food):
            if food=='grass':
                self.weight+=10
                print "weight+10"
            else:
                self.weight-=10
                print "weight-10"
    
    class room:
        def __init__(self,num,animal):
            self.num=num
            self.animal=animal
        def __repr__(self):
            return "room({0.num!s},{0.animal!s})".format(self)
    
    rooms=[]
    for num in range(1,11):
        if num in range(1,6):
            animal=sheep()
        else:
            animal=tiger()
        rlt=room(num,animal)
        rooms.append(rlt)
    
    stime=time.time()
    while True:
        ctime=time.time()
        if ctime-stime>60:
            for r in rooms:
                print "roomnum is {},animal is {},animal_weight is {}".format(r.num,r.animal.name,r.animal.weight)
            break
    
        roomc=rooms[randint(0,9)]
        input=raw_input("num is {},请确定是否选择敲门听动物的声音y/n:".format(roomc.num))
        if input=='y':
            roomc.animal.roar()
        else:
            input_food = raw_input("请给动物喂食:")
            roomc.animal.food(input_food)
  • 相关阅读:
    [LeetCode] 852. Peak Index in a Mountain Array
    [LeetCode] 221. Maximal Square
    [LeetCode] 260. Single Number III
    [LeetCode] 532. K-diff Pairs in an Array
    [LeetCode] 1417. Reformat The String
    [LeetCode] 621. Task Scheduler
    [LeetCode] 454. 4Sum II
    [LeetCode] 18. 4Sum
    [LeetCode] 369. Plus One Linked List
    [LeetCode] 380. Insert Delete GetRandom O(1)
  • 原文地址:https://www.cnblogs.com/pipile/p/12604891.html
Copyright © 2020-2023  润新知