' CLASS_NAME'没有属性' attribute_name'

时间:2015-08-30 11:38:29

标签: python

看看这段代码plz:有规则,在每个实例中,the_oldets必须刷新,Live是一个抽象类

class Live(object):
    _the_oldest = 0

    def __init__(self,age,name):
        self.age=age
        self.name=name

    @classmethod
    def the_oldest(cls):
        if Live._the_oldest < cls.age:
            Live._the_oldest=cls.age

    @staticmethod
    def Print(): 
        print(Live._the_oldest)


class Dog(Live):

    def __init__(self,name,age):
        super().__init__(age,name)
        super().the_oldest()



class Cat(Live):
    def __init__(self,name,age):
        super().__init__(age,name)
        super().the_oldest()

有错误:

>>> db=Dog('doberman',12)
AttributeError: type object 'Dog' has no attribute 'age'

我更改了代码,但没有改变:

class Live(object):
    _the_oldest = 0

    def __init__(self):
        the_oldets(self)

    @classmethod
    def the_oldets(cls):
        if Live._the_oldest < cls.age:
            Live._the_oldest=cls.age

    @staticmethod
    def Print(): 
        print(Live._the_oldest)



class Dog(Live):
    def __init__(self,name,age):
        self.age=age
        self.name=name



class Cat(Live):
    def __init__(self,name,age):
        self.age=age
        self.name=name

结果:

>>> db=Dog('doberman',12)
>>> db.the_oldets()
AttributeError: type object 'Dog' has no attribute 'age'

为什么会发生!以及如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

错误来自cls.age in:

@classmethod
def the_oldest(cls):
    if Live._the_oldest < cls.age:
        Live._the_oldest = cls.age

问题是类cls没有实例所做的属性age。如果该函数不是类方法,则可以写为:

def the_oldest(self):
    if Live._the_oldest < self.age:
        Live._the_oldest = self.age

但是该函数不正确地更新了最旧的函数,因为它只会将它更新为它被调用的对象(如果它更旧)。而不是在问题中隐含的目标是Live._the_oldest包含最早创建的Live子类的年龄,因此更新必须在创建这些实例时完成,而不是在{{{ 1}}因此被调用。

更新可以访问该实例的the_oldest中最早的:

__init__
相关问题