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

标签 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.")

最佳答案

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

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

关于python - 在不创建新属性的情况下降低值的简单方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2582863/

相关文章:

python - Python中的变量是如何分配内存的?

python - 除了被零除之外,double_scalars 遇到溢出的原因是什么?

python - 是否可以在列表和元素中使用相同的切片符号来获得相同的结果?

javascript - 如何在 JavaScript 中创建带有 lang 属性的 HTML 元素?

python - 不是有效 python 标识符的属性

java - 如何从 .java 文件(Java)外部实例化嵌套在类中的类?

python - 我的 Python 电报机器人无法正常工作

c# - 如何通过重复 get 和 setter 来缩短属性

java - 我可以在不实例化此类的情况下使用类的方法吗?

c# - 使用 IL Emit 替换 Activator.CreateInstance