小编Fra*_*ffe的帖子

Python属性错误:类型对象没有属性

我是Python和编程的新手(从12月开始),并尝试自学一些面向对象的Python并在我的lattest项目中得到这个错误:

AttributeError: type object 'Goblin' has no attribute 'color'
Run Code Online (Sandbox Code Playgroud)

我有一个文件来创建"Monster"类和一个从Monster类扩展的"Goblin"子类.当我导入两个类时,控制台不会返回任何错误

>>>from monster import Goblin
>>>
Run Code Online (Sandbox Code Playgroud)

即使创建实例也可以正常工作:

>>>Azog = Goblin
>>>
Run Code Online (Sandbox Code Playgroud)

但是当我调用我的Goblin类的属性时,控制台会在顶部返回错误,我不明白为什么.这是完整的代码:

import random

COLORS = ['yellow','red','blue','green']


class Monster:
    min_hit_points = 1
    max_hit_points = 1
    min_experience = 1
    max_experience = 1
    weapon = 'sword'
    sound = 'roar'

    def __init__(self, **kwargs):
        self.hit_points = random.randint(self.min_hitpoints, self.max_hit_points)
        self.experience = random.randint(self.min_experience,  self.max_experience)
        self.color = random.choice(COLORS)

        for key,value in kwargs.items():
            setattr(self, key, value)

    def battlecry(self):
        return self.sound.upper()


class Goblin(Monster):
    max_hit_points = 3
    max_experience = 2
    sound …
Run Code Online (Sandbox Code Playgroud)

python oop error-handling

3
推荐指数
2
解决办法
4万
查看次数

标签 统计

error-handling ×1

oop ×1

python ×1