Jam*_*Jam 1 python attributes instantiation
我正在制作一个你正在发射"爆炸"的程序,我有5个弹药.我正在爆炸一个有5个健康的外星人.最后,我实例化播放器并让他爆炸6次以检查程序是否正常工作.但是我这样做的方式使得数量不会减少.有没有一个简单的解决方案,或者我只需要为弹药和健康创建一个新的属性?这就是我所拥有的:
class Player(object):
""" A player in a shooter game. """
def blast(self, enemy, ammo=5):
if ammo>=1:
ammo-=1
print "You have blasted the alien."
print "You have", ammo, "ammunition left."
enemy.die(5)
else:
print "You are out of ammunition!"
class Alien(object):
""" An alien in a shooter game. """
def die(self, health=5):
if health>=1:
health-=1
print "The alien is wounded. He now has", health, "health left."
elif health==0:
health-=1
print "The alien gasps and says, 'Oh, this is it. This is the big one. \n" \
"Yes, it's getting dark now. Tell my 1.6 million larvae that I loved them... \n" \
"Good-bye, cruel universe.'"
else:
print "The alien's corpse sits up momentarily and says, 'No need to blast me, I'm dead already!"
# main
print "\t\tDeath of an Alien\n"
hero = Player()
invader = Alien()
hero.blast(invader)
hero.blast(invader)
hero.blast(invader)
hero.blast(invader)
hero.blast(invader)
hero.blast(invader)
raw_input("\n\nPress the enter key to exit.")
Run Code Online (Sandbox Code Playgroud)
想一想:弹药的数量是玩家状态的一部分.对象的状态最好表示为该对象的实例变量.所以你不应该ammo作为一个参数blast- 它应该self.ammo在那个方法中,初始化为5或者__init__你忘记编码的任何东西;-).
这不是寻求花哨的解决方法来隐藏和隐藏其他地方的状态 - 这是以最简单,最直接,最有效的方式做事的问题.为什么你会永远想什么,但这样的方式?
| 归档时间: |
|
| 查看次数: |
7525 次 |
| 最近记录: |