TypeError:'int'对象不可调用,使用模块和对象进行练习

时间:2016-03-13 03:02:11

标签: python python-2.7 oop object module

我是新手编码员。 我刚刚学习了语法,一些关于模块和对象的基础概念。 现在我正试图将所有东西放在小型电脑游戏中。

我创建了两个文件。在“actions.py”文件的末尾,我试图检查“受害者”healthPoints值的变化。在打印测试期间(名为“actions.py”的文件),我在第二个打印语句后得到错误:

Python actions.py 
1) valume of chicken's health: 44 Traceback 
(most recent call last):   File "actions.py", line 17, in <module> fight(dog, chicken)   File "actions.py", line 5, 
in fight damage = attacker.hit() TypeError: 'int' object is not callable

tools.py:

from random import randint
""" Objects in the game """

# Characters
class Character(object):
    """General Class for characters in the game"""
    def __init__(self, name):
        self.name = name
        self.strengh = 0
        self.healthPoints = 0
        damageAtrr = 0

    def hit(self):
        self.hit = self.strengh/2 + randint(1,10) + self.healthPoints / 100
        return self.hit

    def setDamage(self, damage):
        Character.damageAtrr = damage

    def getDamage(self):
        """
        function which take value from
        setDamage and calculate new value for
        healthPoints
        """
        self.healthPoints = self.healthPoints - Character.damageAtrr
        return self.healthPoints


class hero(Character):
    """
    Main character in the game
    """

    def __init__(self, name):
        self.name = name
        self.strengh = 8
        self.healthPoints = 50

class villan(Character):
    """
    Villans in the game
    """

    def __init__(self, name):
        self.name = name
        self.strengh = 5
        self.healthPoints = 50

带有导致问题的功能的第二个文件,“actions.py”:

import tools

# action that causes damage to the victim
def fight(attacker, victim):
    damage = attacker.hit()
    victim.setDamage(damage)
    victim.healthPoints = victim.getDamage()

chicken = tools.hero("Terry")
dog = tools.villan("Max")

#attacker is dog, victim is chicken

fight(dog, chicken)
print "1) valume of chicken's health: %d" % chicken.healthPoints

fight(dog, chicken)
print "2)chicken's health:: %d" % chicken.healthPoints

fight(dog, chicken)
print "3)chicken's health:: %d" % chicken.healthPoints

fight(dog, chicken)
print "4)chicken's health:: %d" % chicken.healthPoints

fight(dog, chicken)
print "5)chicken's health:: %d" % chicken.healthPoints

fight(dog, chicken)
print "6)chicken's health:: %d" % chicken.healthPoints

我不知道究竟是什么导致了这个问题:我预计每当我打电话'打架'时,鸡的健康状况就会降低。

提前感谢您的帮助,对不起我的英语不好

2 个答案:

答案 0 :(得分:0)

tools.py中,您可以定义Character类。在该类中,您定义方法hit()。您稍后在actions.py函数中调用fight()的方法。在hit()中,您说self.hit = ...当您这样做时,您将覆盖self.hit()。在Python中,方法仍然是属性。定义与方法同名的属性时,将覆盖该方法。在这种情况下,除了作为方法之外,您甚至不使用self.hit。在hit()中,只需在self.两次出现之前取出self.hit

答案 1 :(得分:0)

命中字段只是一个属性,但不是Obj的方法。因此,您应该使用:damage = attacker.hit

来访问它