我怎样才能取代" class"在class.function()中有变量吗?

时间:2017-04-29 20:50:24

标签: python python-3.x python-3.5

我正在使用 Python 3.5 。所以这个标题非常令人困惑,我对python还不熟悉,并且不知道如何解决这个问题,也不知道如何给它一个正确的标题。我确实看到了我的逻辑在哪里瑕疵(我打算如何用另一个词轻易地用另一个词取代那个论点超出我的意思)但我仍然不知道解决方案是什么。所以基本上我的问题是试图运行这样的东西:

def attack(self,target):
    target.hp -= self.attack

当我尝试从永久游戏循环中调用它时,这显然不起作用:

opponent = Enemy()
player = Enemy()

if action == "a":
    player.attack(opponent)

我收到错误:

TypeError: 'int' object is not callable

我会粘贴整个代码,以便您可以更好地了解这一点。另外,我很欣赏任何可以在代码中调整以使其更好的提示。在那里,提前谢谢!

import sys
import random

class Enemy:
    def __init__(self, name, hp, attack):
        self.name = name
        self.hp = hp
        self.attack = attack

    def attack(self,target):
        target.hp -= self.attack
        print(target.name +" just lost" + str(self.attack)+"HP")

    def status(self):
        if self.hp <= 0:
            print(self.name +' has just died!')
            sys.exit(0)

        print(self.name +"'s HP:" +str(self.hp))


opponent = Enemy("Goblin",10,1)
player = Enemy("Player",10,2)

while True:
    attackChance = random.randrange(0,2)
    if attackChance == 0:
        print(opponent.name + ": Damn it!\n")
    else:
        opponent.attack(player)

    action = input('Press "a" to attack')
    if action == "a":
        player.attack(opponent)
    else:
        continue

    player.status()
    opponent.status()

3 个答案:

答案 0 :(得分:3)

哦,我明白发生了什么。您声明了属性self.attack和函数self.attack。当你在构造函数中初始化self.attack时,你覆盖了函数 - 当你编写player.attack(opponent)时,Python试图调用一个数字,这会导致错误。

要解决此问题,只需重命名属性或函数。

答案 1 :(得分:1)

您可以将attack设为property来实现。然后在类中,您需要将该值作为私有属性self._attack引用,但该类的用户/客户端可以继续使用attack作为Enemy实例方法。

这就是我的意思(有进一步帮助解释的评论):

import random
import sys

class Enemy:
    def __init__(self, name, hp, attack):
        self.name = name
        self.hp = hp
        self._attack = attack

    @property
    def attack(self):  # getter
        return self._do_attack  # return method

    @attack.setter
    def attack(self, attack):
        self._attack = attack  # change value

    def _do_attack(self, target):
        target.hp -= self._attack  # doesn't use property
        print(target.name +" just lost" + str(self._attack)+"HP")

    def status(self):
        if self.hp <= 0:
            print(self.name +' has just died!')
            sys.exit(0)

        print(self.name +"'s HP:" +str(self.hp))


opponent = Enemy("Goblin",10,1)
player = Enemy("Player",10,2)

while True:
    attackChance = random.randrange(0,2)
    if attackChance == 0:
        print(opponent.name + ": Damn it!\n")
    else:
        opponent.attack(player)

    action = input('Press "a" to attack')
    if action == "a":
        player.attack(opponent)
    else:
        continue

    player.status()
    opponent.status()

action = ''
opponent = Enemy()
player = Enemy()

if action == "a":
    player.attack(opponent)

答案 2 :(得分:0)

self.attack重命名为其他内容。例如,self.attack_points