2021年6月2日
今天主要学习了python中面向对象方面的知识,主要是练习了两道例题。
《奥特曼打怪兽》
import random
import abc
class Fighter(object, metaclass=abc.ABCMeta):
"""战斗者"""
# 通过__slots__魔法限定对象可以绑定的成员变量
__slots__ = ('_name', '_hp')
def __init__(self, name, hp):
"""初始化方法
:param name: 名字
:param hp: 生命值
"""
self._name = name
self._hp = hp
@property
def name(self):
return self._name
@property
def hp(self):
return self._hp
@hp.setter
def hp(self, hp):
self._hp = hp if hp >= 0 else 0
@property
def alive(self):
return self._hp > 0
@abc.abstractmethod
def attack(self, other):
"""攻击
:param other: 被攻击的对象
"""
pass
class Ultraman(Fighter):
__slots__ = ('_name', '_hp', '_mp')
def __init__(self, name, hp, mp):
super().__init__(name, hp)
self._mp = mp
def attack(self, other):
other._hp -= random.randint(15, 25)
def huge_attack(self, other):
if self._mp >= 50:
self._mp -= 50
injury=other._hp*3//4
injury=injury if injury>=50 else 50
other._hp-=injury
return True
else:
self.attack(other)
return False
def magic_attack(self,others):
if self._mp>=20:
self._mp-=20
for temp in others:
if temp.alive:
temp._hp-=random.randint(10,15)
return True
else:
return False
def resume(self):
incr_point=random.randint(1,10)
self._mp+=incr_point
return incr_point
def __str__(self):
return f"{self.name}奥特曼\n"\
f"生命值{self._hp}\n" \
f"魔法值{self._mp}"
class Monster(Fighter):
__slots__ = ('_name','_hp')
def attack(self,other):
other._hp-=random.randint(10,20)
def __str__(self):
return f'{self._name}小怪兽\n' \
f'生命值{self._hp}'
def is_any_alive(monsters):
for monster in monsters:
if monster.alive>0:
return True
return False
def select_alive_one(monsters):
monsters_len=len(monsters)
while True:
index=random.randrange(monsters_len)
monster=monsters[index]
if monster.alive>0:
return monster
def dispaly(ultrman,monsters):
print(ultrman)
for monster in monsters:
print(monster)
def main():
u = Ultraman('骆昊', 1000, 120)
m1 = Monster('狄仁杰', 250)
m2 = Monster('白元芳', 500)
m3 = Monster('王大锤', 750)
ms = [m1, m2, m3]
fight_round = 1
while u.alive and is_any_alive(ms):
print(f"-----------{fight_round}-------")
m=select_alive_one(ms)
skill=random.randint(1,10)
if skill<=6:
print(f"{u.name}使用普通攻击打了{m.name}")
u.attack(m)
print(f"{u.name}能量回了{u.resume()}")
elif skill<=9:
if u.magic_attack(ms):
print(f"{u.name}使用了魔法攻击")
else:
print(f"{u.name}使用魔法失败")
else:
if u.huge_attack(m):
print(f"{u.name}对{m.name}使用了究极必杀")
else:
print(f"{u.name}使用普通攻击打了{m.name}")
print(f"{u.name}能量回了{u.resume()}")
if m.alive>0:
print(f"{m.name}回击了{u.name}")
m.attack(u)
dispaly(u,ms)
fight_round+=1
print("\n战斗结束\n")
if u.alive>0:
print(f"{u.name}胜利")
else:
print("小怪兽胜利")
if __name__ == '__main__':
main()
写的流程主要有:
1.先写父类
(1)限定属性
(2)构造函数
(3)装饰器
(4)公用抽象函数(记得在最前面声明)
2.子类
(1)限定属性
(2)构造函数
调用父类的全部并加上自己特有的
(3)自己独特方法
(4)重写共用函数
写的时候注意的事项:装饰器是空四格写,千万别写成空八格写。
第二道题为《工资结算系统》,大概流程与《奥特曼》类似,一定要内部写的时候要写成self._而不要写成self.
这篇博客记录了作者在2021年6月2日学习Python面向对象编程的内容,包括练习了《奥特曼打怪兽》和《工资结算系统》两个案例。作者详细介绍了如何创建父类和子类,涉及装饰器、构造函数、抽象函数的使用,并强调了装饰器的缩进规范以及在子类中重写父类方法的重要性。
51万+

被折叠的 条评论
为什么被折叠?



