Search code examples
pythonpython-3.xclassinheritancesuper

Python 3 Inheritance Issue


I am a Python novice and I am having difficulty with inheritance and using super()

The code below is giving me this error

Exception has occurred: AttributeError 'ObjB' object has no attribute 'job'

But I'm not sure why as job is an attribute of ObjB

The test code is this..

class ObjA():
    def __init__(self, astr):
        self.name = astr
        self.decorate()

    def decorate(self):
        self.name = '['+self.name+']'

class ObjB(ObjA):
    def __init__(self, aname, ajob):
        super().__init__(aname)
        self.job = ajob

    def decorate(self):
        super().decorate()
        self.name = self.name + ' is a ' + self.job

test = ObjA('Fred')
print(test.name)

test2 = ObjB('Fred', 'Baker')
print(test2.name)

What I was expecting was this

[Fred]
[Fred] is a Baker

Solution

  • In your ObjB.__init__() method you are calling super().__init__(aname) before you set self.job = ajob, so that when the decorate methods are called, the self.job is not yet set. Try moving the self.job = ajob earlier in the __init__() method, like:

    class ObjB(ObjA):
        def __init__(self, aname, ajob):
            self.job = ajob
            super().__init__(aname)
    

    Another way to fix the problem is to eliminate the decorate() methods completely:

    class ObjA():
        def __init__(self, astr):
            self.name = '['+astr+']'
    
    
    class ObjB(ObjA):
        def __init__(self, aname, ajob):
            super().__init__(aname)
            self.job = ajob
            self.name = self.name + ' is a ' + self.job