-1

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

MafMal
  • 71
  • 5
  • 2
    You never called `Result.__init__`; it's `super(AdditionResult, self).__init__()` or just `super().__init__()`. Your call to `super` jumped straight to `object.__init__`. – chepner Mar 25 '22 at 21:23

1 Answers1

0

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__()
azro
  • 53,056
  • 7
  • 34
  • 70