封装示例:游戏开发
封装示例:游戏开发
## 初级!!!
class Police:
def __init__(self,name):
self.nam = name #从左至右赋值
self.hp = 10000#警察初始生命值
def tax(self):
msg = "%s收了个税"%(self.nam)
print(msg)
def fight(self):
msg = "%战了个斗" % (self.nam)
lsq = Police("李少奇")
lsq.tax()
zzh = Police("抓抓会")
tyg = Police("唐油光")
class Feitu:
def __init__(self,nickname):
self.nickname = nickname
self.hp = 1000 #匪徒初始生命值
def murder(self,name):
msg = "%s去谋杀了%s"%(self.nickname,name)
print(msg)
yzl = Feitu("灰鹰")#属性赋值,定义秃鹰的属性
yzq = Feitu("秃鹫")
qtz = Feitu("擎天柱")
#1.灰鹰谋杀李少奇,灰鹰的生命值减少100,李少奇生命值减少5000
yzl.murder(lsq.nam)#找到murder函数
yzl.hp = yzl.hp - 100
lsq.hp = lsq.hp - 5000
print(yzl.hp,lsq.hp)
#利用init对其进行属性进行定性
## 进阶!!!
class Police:
def __init__(self,name):
self.name = name
self.hp = 10000#警察初始生命值,自动获得
def dao(self,other):
msg = "%s给了%s一刀"%(self.name,other.nickname)
self.hp = self.hp - 10
other.hp = other.hp - 50
print(msg)
def quan(self,other):
msg = "%s给了%s一拳" % (self.name,other.nickname)
self.hp = self.hp - 5
other.hp = other.hp - 25
print(msg)
class Feitu:
def __init__(self,nickname):
self.nickname = nickname #self.nickname 可以改为self.nick,但对于line14传递后参数的.nicknam的方向存疑?
self.hp = 1000 #匪徒初始生命值,自动获得
def gun(self,other):
msg = "%s给了%s一枪" % (self.nickname,other.name)
self.hp = self.hp - 100
other.hp = other.hp - 500
print(msg)
yzl = Feitu("灰鹰")
lsq = Police("李少奇") #此时为带参数的函数
lsq.dao(yzl) #将参数代入dao的函数中,然后dao也需要参数,此时yzl其实是一个函数,所以此时可以调用other.hp
lsq.quan(yzl)
yzl.gun(lsq)
# 无论对于police或者Feitu,需要通过init所获得属性有1.name 2.初始hp(生命值)
#思考:
#为什么要这样做???
#1.将不同得到函数进行分类,便于归纳总结(类套函数,层层封装)
#2.将类进行现成的封装,便于多个不同的参数传入调用,增强代码段的可用性
#3.制造科学黑箱,方便调用及外接
记录学习的点点滴滴