Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Inheritance – Access base classes attribute

I created 2 classes, Result is the base for AdditionResult. What did I miss to access the base classes attribute (results) ?

import sys
class Result:
    CATEGORY = 'foo'

    def __init__(self):
        self.results = {}


class AdditionResult(Result):
    CATEGORY = 'addition'

    def __init__(self, a, b):
        super(Result, self).__init__()
        self.a = a
        self.b = b

        # debug
        print(self.__class__)
        print(self.__class__.__base__)
        print(self.__dict__)

    def calculate(self):
        self.results[AdditionResult.CATEGORY] = self.a + self.b


if __name__ == '__main__':
    print(sys.version)
    sr = AdditionResult(3, 8)
    sr.calculate()

Result is:

3.6.6 (v3.6.6:4cf1f54eb7, Jun 27 2018, 03:37:03) [MSC v.1900 64 bit (AMD64)]
<class '__main__.AdditionResult'>
<class '__main__.Result'>
{'a': 3, 'b': 8}
Traceback (most recent call last):
  File "C:\temp\i.py", line 29, in <module>
    sr.calculate()
  File "C:\temp\i.py", line 23, in calculate
    self.results[AdditionResult.CATEGORY] = self.a + self.b
AttributeError: 'AdditionResult' object has no attribute 'results'

I expected to be able access self.results

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Problem

You broke the super call : you’re calling Result.__init__ because
super(Result, self).__init__() means :

call the parent class of Result with instance self


Fix

What you want is the parent of AdditionResult so super(AdditionResult, self).__init__()


Improve

Use the empty argument version

class AdditionResult(Result):
    def __init__(self, a, b):
        super().__init__()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading