Python类继承:AttributeError:'[SubClass]'对象没有属性'xxx' [英] Python class inheritance: AttributeError: '[SubClass]' object has no attribute 'xxx'

查看:967
本文介绍了Python类继承:AttributeError:'[SubClass]'对象没有属性'xxx'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下基类和子类:

class Event(object):
    def __init__(self, sr1=None, foobar=None):
        self.sr1 = sr1
        self.foobar = foobar
        self.state = STATE_NON_EVENT

# Event class wrappers to provide syntatic sugar
class TypeTwoEvent(Event):
    def __init__(self, level=None):
        self.sr1 = level
        self.state = STATE_EVENT_TWO

在我的代码中,我正在检查TypeTwoEvent类的实例,检查我知道的字段是否存在于基础中class - 我预计它默认值为None。但是,我的代码引发了以下异常:

Further on in my code, I am inspecting an instance of a TypeTwoEvent class, checking for a field I know exists in the base class - I expected it to be defaulted to value None. However, my code raises the following exception:


AttributeError:'TypeTwoEvent'对象没有属性'foobar'

AttributeError: 'TypeTwoEvent' object has no attribute 'foobar'

我认为基类字段将由子类继承,并且创建子类的实例将实例化基类(因此调用它的构造函数)...

I was under the impression that the base class fields would be inherited by the sub class and that creating an instance of a sub class will instantiate the base class (and thus invoke its constructor) ...

我在这里缺少什么?为什么 TypeTwoEvent 没有 foobar 属性 - 当派生它的基类具有<$ c $时c> foobar 属性?

What am I missing here?. Why does TypeTwoEvent not have a foobar attribute - when the base class from which it is derived has a foobar attribute?

推荐答案

你的子类应该是:

class TypeTwoEvent(Event):

    def __init__(self, level=None, *args, **kwargs):
        super(TypeTwoEvent, self).__init__(*args, **kwargs)
        self.sr1 = level
        self.state = STATE_EVENT_TWO

因为你覆盖了 __ init __ 方法,所以如果你希望父行为发生,你需要调用父方法。

Because you override the __init__ method, so you need to call the parent method if you want the parent behavior to happen.

请记住, __ init __ 并不是一种特殊的方法,它会抛出其奇怪的名字。它只是在创建对象后自动调用的方法。否则它是一个普通的方法,普通继承规则适用。

Remember, __init__ is not a special method dispite its strange name. It's just the method automatically called after the object is created. Otherwise it's an ordinary method, and ordinary inheritance rules apply.

super(ClassName, self).__init__(arguments, that, goes, to, parents)

是调用方法父版本的语法。

is the syntax to call the parent version of the method.

对于 * args ** kwargs ,它只是确保我们捕获所有其他参数传递给 __ init __ 并将其传递给父方法,因为您的子方法签名没有这样做,并且父级需要这些参数才能工作。

For *args and **kwargs, it just ensures we catch all additional arguments passed to __init__ and pass it to the parent method, as you child method signature didn't do it and the parent need these arguments to work.

这篇关于Python类继承:AttributeError:'[SubClass]'对象没有属性'xxx'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆