1.封装
#1.将属性和方法封装到一个抽象的类中
#2.外界使用类创建对象,对象调用方法
#3.对象方法的细节都被封装在类的内部
-------->题目要求:
需求:
1.李雷体重75.0公斤
2.李雷每次跑步会减肥0.5公斤
3.李雷每次吃东西体重会增加1公斤
-------->代码如下:
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
Lilei = Person('李雷',75.0)
Lilei.run()
print(Lilei)
Lilei.eat()
print(Lilei)
-------->测试结果:
2.练习
练习(一)
-------->(1)题目要求:
需求:
1.房子有户型,总面积和家具名称列表
新房子没有任何的家具
2.家具有名字和占地面积,其中
床:占4平米
衣柜:占2平米
餐桌:占1.5平米
3.将以上三件家具添加到房子中
4.打印房子时,要求输出:户型,总面积,剩余面积,家具名称列表
-------->代码如下:
class Furniture():
def __init__(self,name,area):
self.name = name
self.area = area
def __str__(self):
return '[%s]占地: %.2f' %(self.name,self.area)
# bed = Furniture('bed',4)
# print(bed)
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):
#1.判断家具的面积
if item.area > self.free_area:
print('%s 的面积太大,无法添加' %item.name)
#2.添加家具
self.item_list.append(item.name)
#3.计算剩余面积
self.free_area -= item.area
bed = Furniture('bed',4)
print(bed)
yigui = Furniture('yigui',200)
print(yigui)
table = Furniture('table',1.5)
print(table)
my_house = House('独门独栋',400)
my_house.add_item(bed)
my_house.add_item(yigui)
my_house.add_item(table)
print(my_house)
-------->测试结果:
练习(二)
-------->(2)题目要求:
1.士兵瑞恩有一把AK47
2.士兵可以开火(士兵开火扣动的是扳机)
3.枪 能够 发射子弹(把子弹发射出去)
4.枪 能够 装填子弹 --增加子弹的数量
简单方法:
Soldier Gun
name model
gun bullet_count #子弹数量足够多才能完
成射击的动作
init(self): init(self):
fire(self): add_bullet(self,count):#装填子弹的
方法
shoot(self):
-------->代码如下:
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)
self.bullet_count -= 1
print('%s ... %s' %(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)
self.gun.add_bullet(5)
self.gun.shoot()
ak47 = Gun('ak47')
ak47.add_bullet(20)
ak47.shoot()
ryan = Soldier('Ryan')
ryan.gun = ak47
ryan.fire()
-------->测试结果:
标签:__,封装,name,area,Python,self,面向对象,item,def
来源: https://blog.csdn.net/qq_39376481/article/details/89219488