1.打印小猫爱吃鱼,小猫要喝水
class Cat:
def eat(self):
print '小猫爱吃鱼'
def drink(self):
print '小猫要喝水'
tom = Cat()
tom.eat()
tom.drink()
2.小明爱跑步,爱吃东西。
1)小明体重75.0公斤
2)每次跑步会减肥0.5公斤
3)每次吃东西体重会增加1公斤
4)小美的体重是45.0公斤
class Person:
def __init__(self, name, weight):
self.name = name
self.weight = weight
def __str__(self):
return '我的名字叫 %s 体重是 %.2f' % (self.name, self.weight)
def run(self):
print '%s 爱跑步' % self.name
self.weight -= 0.5
def eat(self):
print '%s 吃东西' % self.name
self.weight += 1
xx = Person('小明', 75.0)
xx.run()
xx.eat()
print xx
xm = Person('小美', 45.0)
xm.run()
xm.eat()
print xm
print xx
3.摆放家具
需求:
1).房子有户型,总面积和家具名称列表
新房子没有任何的家具
2).家具有名字和占地面积,其中
床:占4平米
衣柜:占2平面
餐桌:占1.5平米
3).将以上三件家具添加到房子中
4).打印房子时,要求输出:户型,总面积,剩余面积,家具名称列表
class HouseItem:
def __init__(self, name, area):
self.name = name
self.area = area
def __str__(self):
return '[%s] 占地 %.2f' % (self.name, self.area)
class House:
def __init__(self, house_type, area):
self.house_type = house_type
self.area = area
self.free_area = area
self.item_list = []
def __str__(self):
return '户型:%s\n总面积:%.2f[剩余:%.2f]\n家具:%s' % (self.house_type, self.area, self.free_area, self.item_list)
def add_item(self, item):
print '要添加 %s' % item
if item.area > self.free_area:
print '%s 的面积太大了,无法添加' % item.name
return
self.item_list.append(item.name)
self.free_area -= item.area
bed = HouseItem('bed', 400)
print bed
chest = HouseItem('chest', 2)
print chest
table = HouseItem('table', 1.5)
print table
my_home = House('两室一厅', 60)
my_home.add_item(bed)
my_home.add_item(chest)
my_home.add_item(table)
print my_home
4.需求:
1).士兵瑞恩有一把AK47
2).士兵可以开火(士兵开火扣动的是扳机)
3).枪 能够 发射子弹(把子弹发射出去)
4).枪 能够 装填子弹 --增加子弹的数量
class Gun:
def __init__(self, model):
self.model = model
self.bullet_count = 0
def add_bullet(self, count):
self.bullet_count += count
def shoot(self):
if self.bullet_count <= 0:
print '[%s] 没有子弹了...' % self.model
return
self.bullet_count -= 1
print '[%s] 突突突...[%d]' %(self.model,self.bullet_count)
class Soldier:
def __init__(self,name):
self.name = name
self.gun = None
def fire(self):
if self.gun == None:
print '[%s] 还没有枪' %self.name
return
print 'go!!! [%s]' %self.name
self.gun.add_bullet(50)
self.gun.shoot()
ak47 = Gun('AK47')
ryan = Soldier('Ryan')
ryan.gun = ak47
ryan.fire()
5.打印tom来了,我是tom和tom走了
class Cat:
def __init__(self, new_name):
self.name = new_name
print '%s 来了' % self.name
def __del__(self):
print '%s 走了' % self.name
def __str__(self):
return '我是 %s' % self.name
tom = Cat('Tom')
print tom
6.图书管理系统
1. 查询
2. 增加
3. 借阅
4. 归还
5. 退出
class Book(object):
def __init__(self, name, author, state, bookIndex):
self.name = name
self.author = author
# 0:借出 1:未借出
self.state = state
self.bookIndex = bookIndex
def __str__(self):
return "书名:《%s》 作者:<%s> 状态:<%s> 位置:<%s>" % (self.name, self.author, self.state, self.bookIndex)
class BookManage(object):
books = []
def start(self):
"""图书管理初始化"""
b1 = Book('python', 'Guido', 1, "INS888")
self.books.append(b1)
self.books.append(Book('java', 'hello', 1, "IGS888"))
self.books.append(Book('c', 'westos', 1, "INS880"))
def menu(self):
self.start()
while True:
print("""
图书管理系统
1. 查询
2. 增加
3. 借阅
4. 归还
5. 退出
""")
choice = raw_input("Choice:")
if choice == '1':
name = raw_input("书名:")
self.checkBook(name)
elif choice == '2':
self.addBook()
elif choice == '3':
self.borrowBook()
else:
print("请输入正确的选择!")
def addBook(self):
name = raw_input("书名:")
self.books.append(Book(name, raw_input("作者:"), 1, raw_input("书籍位置:")))
print("添加图书%s成功!" % (name))
def borrowBook(self):
name = raw_input("借阅书籍名称:")
ret = self.checkBook(name)
if ret != None:
if ret.state == 0:
print("书籍《%s》已经借出" % (name))
elif ret.state == 1:
print("借阅《%s》成功" % (name))
ret.state = 0
else:
print("书籍《%s》不存在!" % (name))
def checkBook(self, name):
for book in self.books:
if book.name == name:
# 返回book对象
print book
return book
else:
return None
bookManage = BookManage()
bookManage.menu()
7.打印‘人和狗玩‘,‘狗自己玩’
class Dog(object):
def __init__(self,name):
self.name = name
def play(self):
print '%s 蹦蹦跳跳的玩' %self.name
class XiaotianDog(object):
def __init__(self,name):
self.name = name
def play(self):
print '%s 飞上天玩' %self.name
class Person(object):
def __init__(self,name):
self.name = name
def play_with_dog(self,Dog):
print '%s 和 %s 一起玩' %(self.name,Dog.name)
Dog.play()
#1.创建一个狗对象
#wangcai = Dog('旺财')
wangcai = XiaotianDog('旺财')
#2.创建一个人对象
xiaoming = Person('小明')
#1.让小明调用狗,和狗玩
xiaoming.play_with_dog(wangcai)
8.记录所有工具的数量
class Tool(object):
count = 0
def __init__(self, name):
self.name = name
# 让类属性+1
Tool.count += 1
tool1 = Tool('斧头')
tool2 = Tool('锤头')
print Tool.count
9.记录所有玩具的数量
class Toy(object):
count = 0
@classmethod
def show_toy_count(cls):
print '玩具对象的数量是 %d' % cls.count
def __init__(self, name):
self.name = name
Toy.count += 1
toy1 = Toy('乐高')
toy2 = Toy('小熊')
Toy.show_toy_count()
10.打印‘喵喵’
class Cat(object):
# 不访问实例属性或类属性
@staticmethod
def call():
print '喵喵~'
#不需要创建对象直接就可以使用
Cat.call()
11.1).设计一个Game类
2).属性
定义一个属性top_score记录游戏的历史最高分
定义一个属性player_name记录当前游戏玩家姓名
3).方法
show_help显示游戏帮助信息
show_top_score显示历史最高分
show_game开始当前玩家的游戏
import random
class Game(object):
top_score = 0
def __init__(self, player_name):
self.player_name = player_name
@staticmethod
def show_help():
print """
帮助:
输入show_help显示游戏帮助信息
show_top_score显示历史最高分
show_game开始当前玩家的游戏
"""
@classmethod
def show_game(cls):
print '游戏开始拉'
Game.score = random.randint(1, 100)
print '你的分数为:%d' % Game.score
if Game.score >= cls.top_score:
cls.top_score = Game.score
else:
cls.top_score = cls.top_score
@classmethod
def show_top_score(cls):
print '历史最高分为:%d' % Game.top_score
xiaoming = Game('小明')
Game.show_help()
Game.show_game()
Game.show_game()
Game.show_top_score()
11.@1两个播放器可以同时开启
class MusicPlayer(object):
def __new__(cls, *args, **kwargs):
print '创建对象,分配空间'
instance = object.__new__(cls)
return instance
def __init__(self):
print '初始化播放器'
player1 = MusicPlayer()
print player1
player2 = MusicPlayer()
print player2
@2两个播放器公用同一个空间
class MusicPlayer(object):
instance = None
def __new__(cls, *args, **kwargs):
if cls.instance is None:
cls.instance = object.__new__(cls)
return cls.instance
def __init__(self):
print '初始化播放器'
player1 = MusicPlayer()
print player1
player2 = MusicPlayer()
print player2
@3优化,两个播放器公用一个地址空间
class MusicPlayer(object):
instance = None
init_flag = False
def __new__(cls, *args, **kwargs):
if cls.instance is None:
cls.instance = object.__new__(cls)
return cls.instance
def __init__(self):
if MusicPlayer.init_flag:
return
print '初始化播放器'
MusicPlayer.init_flag = True
player1 = MusicPlayer()
print player1
player2 = MusicPlayer()
print player2
12.输入一个整数,输出8除以这个整数的值。
try:
num = int(raw_input('输入一个整数:'))
result = 8 / num
print result
except ZeroDivisionError:
print '0不能做除数'
except ValueError:
print '输入的值不是数字'
except Exception as result:
print '未知错误 %s' %result
finally:
print '无论是否有异常都会执行的代码'
print '*'
13.输入一个不少于八位的密码
14.输入div判断div不能等于0.错误时报错
def func(num, div):
assert (div != 0), 'div不能为0'
return num / div
print func(10, 0)