Skip to main content
 首页 » 编程设计

python之在不创建新属性的情况下降低值的简单方法

2025年05月04日10shanyou

我正在制作一个程序,您可以在其中发射“爆能枪”,而我有 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.") 

请您参考如下方法:

想一想:可用弹药的数量是玩家状态的一部分。对象的状态最好表示为该对象的实例变量。所以你应该不将 ammo 作为 blast 的参数——在那个方法中它应该是 self.ammo ,初始化为 5 或 __init__ 中你忘记编码的任何内容;-)。

这不是寻找花哨的变通方法来隐藏和隐藏该状态的问题,而是以最简单、最直接、最有效的方式做事的问题。为什么你曾经不想要这样的方式?!