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

Fra*_*ffe 3 python oop error-handling

我是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 = 'squiek'
Run Code Online (Sandbox Code Playgroud)

Seb*_*ann 9

您没有创建实例,而是引用类Goblin本身,如错误所示:

AttributeError:类型对象'Goblin'没有属性'color'

将您的行更改为 Azog = Goblin()


小智 5

当你赋值时Azog = Goblin,你不是在实例化一个 Goblin。试试吧Azog = Goblin()