遇到课程问题

时间:2013-04-26 21:34:41

标签: python python-3.x

我正在尝试转换我为计算单个“损坏”输出而制作的函数,我不明白我哪里出错了。作为一个函数,它正常处理我的方法,但是当我成为一个类时,我收到一个未找到的全局名称。另外,我认为我的 init 是正确的,但我可能错了。

import random

class Damage(object):
    """Represents 1 single damage value"""

    def __init__(self):
        """Constructor initializes objects attributes. stats."""
        ### I need to initialize my stats from a different class since they
        ### are not a constant. self._statList is a dictionary that will be
        ### imported.
        self._statList = {"strength":100, "hitStat":90, "eBlockchance":10, \
                          "critStat":15, "defense":0}
        self._strength = self._statList["strength"]
        self._hitStat  = self._statList["hitStat"]
        self._eBlockchance = self._statList["eBlockchance"]
        self._defense = self._statList["defense"]
        self._critStat = self._statList["critStat"]

    def __str__(self):
        """Returns string representation of the damage"""
        self._base = self._strength - self._defense
        self._damage = random.randint(self._base/2, self._base)
        ### I have no idea why this isn't running my methods below.
        ### NameError: global name 'hitChance' is not defined.
        if hitChance() == True:
            return "Miss"
        else:
            if enemyBlock() == True:
                return "Block"
            else:
                if critChance() == True:
                    return str(self._damage*2) + "CRITICAL"
                else:
                    return str(self._damage)

    def critChance(self):
        self._chance = random.randint(1,100)
        if self._chance <= self._critStat:
            return True

    def enemyBlock(self):
        self._chance = random.randint(1,100)
        if self._chance <= self._eBlockchance:
            return True

    def hitChance(self):
        self._chance = random.randint(1,100)
        if self._chance > self._hitStat:
            return True

1 个答案:

答案 0 :(得分:5)

你有类似的地方:

if hitChance() == True:

需要:

if self.hitChance() == True:

就像self这样的成员变量需要明确的self._strength一样,你也需要它用于方法。