Python object deleting itself

后端 未结 14 2004
一向
一向 2020-11-27 04:23

Why won\'t this work? I\'m trying to make an instance of a class delete itself.

>>> class A():
    def kill(self):
        del self


>>>          


        
14条回答
  •  长情又很酷
    2020-11-27 04:43

    I am trying the same thing. I have a RPG battle system in which my Death(self) function has to kill the own object of the Fighter class. But it appeared it`s not possible. Maybe my class Game in which I collect all participants in the combat should delete units form the "fictional" map???

       def Death(self):
        if self.stats["HP"] <= 0:
            print("%s wounds were too much... Dead!"%(self.player["Name"]))
            del self
        else:
            return True
    
    def Damage(self, enemy):
        todamage = self.stats["ATK"] + randint(1,6)
        todamage -= enemy.stats["DEF"]
        if todamage >=0:
            enemy.stats["HP"] -= todamage
            print("%s took %d damage from your attack!"%(enemy.player["Name"], todamage))
            enemy.Death()
            return True
        else:
            print("Ineffective...")
            return True
    def Attack(self, enemy):
        tohit = self.stats["DEX"] + randint(1,6)
        if tohit > enemy.stats["EVA"]:
            print("You landed a successful attack on %s "%(enemy.player["Name"]))
            self.Damage(enemy)
            return True
        else:
            print("Miss!")
            return True
    def Action(self, enemylist):
        for i in range(0, len(enemylist)):
            print("No.%d, %r"%(i, enemylist[i]))
        print("It`s your turn, %s. Take action!"%(self.player["Name"]))
        choice = input("\n(A)ttack\n(D)efend\n(S)kill\n(I)tem\n(H)elp\n>")
        if choice == 'a'or choice == 'A':
            who = int(input("Who? "))
            self.Attack(enemylist[who])
            return True
        else:
            return self.Action()
    

提交回复
热议问题