Python类实现困难

时间:2017-05-19 11:19:50

标签: python class

每当我尝试在python空闲时运行此代码时,它表示我的缩进不正确,并且我做了很多改动以尝试让它运行,但没有一个工作。你能给我什么建议让它运作起来吗?

from random import randint
class enemy:
    def __init__(self, type, bhealth, dmglvl):
        self.type = type
        self.bhealth = int(bhealth)
        self.dmglvl = int(dmglvl)
        enhealth=self.bhealth
    def eninfo(self):
        return '{} {} {}'.format(self.type, self.bhealth, self.dmglvl)
    def battleintro(self):
        return 'an enemy {} has appeared! \nIt has: {} health.'.format(self.type, self.bhealth)
    def hit(self):
        print('You swing your sword at the {}.'.format(self.type))
        chardmg=randint(8,15)
        enhealth-=chardmg
        print('You deal {} damage. The {} has {} hit-points left.'.format(chardmg, self.type, enhealth))
        if enhealth <=1:
            return 'The {} Died!'.format(self.type)
enemy1 = enemy("goblin", 15, 1)
print(enemy1.eninfo())
print(enemy1.battleintro())

1 个答案:

答案 0 :(得分:0)

您是将其键入文件,还是想直接将其输入交互式解释器 - 空闲时打开默认屏幕?

交互式intrepreter用于测试和短代码序列,不是为了尝试键入整个类 - 但总体而言,它确实与您在实际程序文件中键入的内容有一些关键差异:最有用的是在代码块的末尾,你必须跳过一行(即一个额外的空行) - 否则它会给你一个错误。

所以你必须在你的&#34; enmey1 = ...&#34;之前加入一种白色素。 line - 但是,您必须将其键入为&#34; myfile.py&#34;文件,而不是在解释器中,然后运行&#34; import myfile&#34;以交互方式测试它。

相关问题