1

Consider this example with python dataclasses. I am using Python 3.10:

from dataclasses import dataclass

@dataclass(slots=True)
class A:
    a: int
    
    def __init__(self, a: int):
        self.a = a


@dataclass(slots=True)
class B(A):
    b: int
    
    def __init__(self, a: int, b: int):
        super().__init__(a)  # Raises Exception below
        self.b = b

This raises the following exception:

TypeError: super(type, obj): obj must be an instance or subtype of type

Note that in the actual production example it is necessary to manually define the __init__s. Otherwise, this problem does not appear.

I don't understand why. How do I fix this?

If for class B I remove slots=True everything works. Also, if I add the slots manually in class B, it also works.

HerpDerpington
  • 3,751
  • 4
  • 27
  • 43
  • 1
    Because using this form of `super` will reference the actual class where it is defined, but using `slots` makes the decorator return *a new distinct class object*, so now the instance (self) will no longer be an instance of the type being passed as the first argume t – juanpa.arrivillaga Aug 11 '22 at 23:58

0 Answers0