Python class inheritance: AttributeError: '[SubClass]' object has no attribute 'xxx'

后端 未结 5 1766
时光说笑
时光说笑 2020-12-10 00:51

I have the following base class and subclass:

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


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 01:33

    You're overriding the constructor (__init__) of the parent class. To extend it, you need to explicitly call the constructor of the parent with a super() call.

    class TypeTwoEvent(Event):
        def __init__(self, level=None, **kwargs):
            # the super call to set the attributes in the parent class
            super(TypeTwoEvent, self).__init__(**kwargs)
            # now, extend other attributes
            self.sr1 = level
            self.state = STATE_EVENT_TWO
    

    Note that the super call is not always at the top of the __init__ method in your sub-class. Its location depends on your situation and logic.

提交回复
热议问题