AttributeError:“NoneType”对象没有属性“nam”

2024-09-27 00:22:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python和编程新手。我试图创建一个简单的(目前)文本游戏和有一个问题。这是我有问题的部分代码

 class Monster:
         def __init__(self,name,hp,ac,exp,thaco):
            self.name=name
            self.hp=hp
            self.ac=ac
            self.exp=exp
            self.thaco=thaco


    class Zombie(Monster):
        def __init__(self):
            super().__init__(name="Zombie",
                             hp=10,ac=5,
                             exp=1,thaco=20)

        POWER=[1,2,3,4,5,6,7]

    class Ghul(Monster):
        def __init__(self):
            super().__init__(name="Ghul",
                             hp=12,ac=6,
                             exp=1,thaco=20)

        POWER=[1,2,3,4,5,6]

    class Skeleton(Monster):
        def __init__(self):
            super().__init__(name="Skeleton",
                             hp=6,ac=2,
                             exp=1,thaco=20)

        POWER=[1,2,3,4]

    class Ghost(Monster):
        def __init__(self):
            super().__init__(name="Ghost",
                             hp=5,ac=10,
                             exp=2,thaco=20)

        POWER=[1,2,3,4,5,6]


    class Slime(Monster):
        def __init__(self):
            super().__init__(name="Slime",
                             hp=26,ac=8,
                             exp=4,thaco=20)

        POWER=[5,6,7,8,9,10]


    def random_mob():
            while twenty_sided_die.roll() <=5 :
                mob=Zombie()
                return mob
            while 5 < twenty_sided_die.roll() <= 10:
                mob=Ghul()
                return mob
            while 10 < twenty_sided_die.roll() <= 15:
                mob=Skeleton()
                return mob
            while 15 < twenty_sided_die.roll() <= 19:
                mob=Ghost()
                return mob
            while twenty_sided_die.roll() > 19:
                mob=Slime()
                return mob


        mob = random_mob()
for command, action in hero.COMMANDS.items():
    print("Press {} to {}".format(command, action[0]))
while True:
    command = input("~~~~~~~Press key to continue~~~~~~~")
    if command not in hero.COMMANDS:
        print("Not a valid command")
        continue
    print("You are fighting "  + mob.name)
    time.sleep(1)
    print("")
    break

问题是在代码的最后一部分打印暴徒战斗。 我每次都会犯错误:

AttributeError:'NoneType'对象没有属性'名称,我找不到任何原因。在

如有任何建议,敬请谅解


Tags: nameselfinitdefacclasshpmob
1条回答
网友
1楼 · 发布于 2024-09-27 00:22:56

错误来自您的random_mob函数。试试这个:

def random_mob():
        roll = twenty_sided_die.roll()
        if roll <= 5 :
            return Zombie()
        elif roll <= 10:
            return Ghul()
        elif roll <= 15:
            return Skeleton()
        elif roll <= 19:
            return Ghost()
        else:
            return Slime()

说明:你应该只掷骰子一次,存储结果并在所有子范围内进行测试。在原始函数中,将骰子掷几次,就有机会让所有测试返回False,这意味着该函数返回None

相关问题 更多 >

    热门问题