Python在类函数之间错误地传递变量?

2024-06-26 01:31:39 发布

您现在位置:Python中文网/ 问答频道 /正文

这个程序相当不言自明。我已经开始学习Python的基础知识了,我对这一点非常迷恋。我习惯于C++和通过引用传递事物的奇妙能力。但是,在这里,我要改变的类变量(战士。守护神)不会改变,我读到这是因为整数是不可变的,它只是在本地创建一个新的对象。那么,我该如何将更改应用于原始变量呢?我搜索了又搜索,但都没有结果。我不想表演一些丑陋的曼纽尔,比如列一张单子,如果不必要的话就传给他。在

#python 3.2.2

#   Create a small test project to have combat between two entities.    #
#   Combat should include 3 different stats: statATK, statDEF, and statHEALTH.  #
#   The two entities should be of the same class.   #

class Fighter:
    def __init__(self):
        self.statHEALTH = 10
        self.statATK = 3
        self.statDEF = 3

    def attack(self, enemyhealth):
        enemyhealth = (enemyhealth - self.statATK)
        return enemyhealth

    def defend(self):
        statDEF += 1


def main():
    James = Fighter()
    Keaton = Fighter()
    while James.statHEALTH > 0:
        print("Do you wish to attack or defend?")
        print("1. Attack")
        print("2. Defend")
        choice = input()
        if choice == "1":
            James.attack(Keaton.statHEALTH)
            print("You did", James.statATK, "damage!") 
            Keaton.attack(James.statHEALTH)
            print("Keaton has", Keaton.statHEALTH, "health left.")
            print("Keaton did", Keaton.statATK, "damage!")
            print("You have", James.statHEALTH, "health left.")
        #elif choice == "2":
            #James.defend()
            #Keaton.attack(James.statHEALTH)

main()

Tags: toselfdefhaveprintchoiceattackjames
3条回答

试着做:

while James.statHEALTH > 0:
    #print statements
    if choice == "1":
        the_attack = James.attack(Keaton)

然后将类定义为:

^{pr2}$

这还有一个很容易扩展的好处,例如,您可以为某些元素添加命中表(for i in random.randint(1,100) if i < 20: #miss; elif 20 <= i < 80: #hit; elif 80<= i: #crit)或抵抗,或者添加一个标志,允许您的防御者在其takedamage函数中进行反击(可能调用一个新函数getcountered以防止无限循环)。在

也许你可以换个角度想。在您的例子中,Fighter.attack()只返回攻击后敌人的生命值。所以说真的,它应该是对敌人对象的方法调用。你可以添加一种方法,当战士受到攻击时,降低他们的生命值:

def attack(self, enemy):
    enemy.getAttacked(self.statATK)

def getAttacked(self, ATK):
    self.statHEALTH -= ATK
def attack(self, enemyhealth):
    enemyhealth = (enemyhealth - self.statATK)
    return enemyhealth

如果你把电话改成

^{pr2}$

。。因为你return攻击造成的伤害。显然,这很难看;重复你自己是不好的。相反,您可以使attack看起来像:

def attack(self, other):
    other.statHEALTH -= self.statATK

然后就这么做

James.attack(Keaton)

当你打电话的时候。在

相关问题 更多 >