0

Using the example below, How can I ensure that any class that inherits the AdderMixin has the property x. This would be done at class definition stage.

class AdderMixin:
    x: int

    @classmethod
    def add(cls, other):
        return cls.x + other


class B(AdderMixin):
    x = 3


class C(AdderMixin):
    pass

# I would like an error to be raised by here, 
# as C inherited AdderMixin without defining x

print(B.add(4))
print(C.add(5))  # actually errors here.
A H
  • 2,164
  • 1
  • 21
  • 36
  • You could do that with metaclasses, see e.g. https://docs.python.org/3/library/abc.html – jonrsharpe Apr 28 '19 at 14:07
  • Thanks, but I only know how to do it using abstract classes when instantiating the class (i.e. ``c = C() # this will raise an error``), and not when defining the class. – A H Apr 28 '19 at 14:14
  • Yes, that's what the ABCs do. They also use metaclasses, was my point, and have *similar* functionality to what you want. – jonrsharpe Apr 28 '19 at 14:14
  • You might be looking for `property` this might help: https://www.programiz.com/python-programming/property – Daniel Butler Apr 28 '19 at 14:26
  • Define `x` as an abstract property on an ABC. The subclasses can implement it as a straight-up attribute: as long as the name is present. – Martijn Pieters Apr 28 '19 at 14:32
  • **However**: ABCs only prevent instances being created, class creation is not prohibited. You can enforce class attributes with a `__init_subclass__` method on `AdderMixin`. – Martijn Pieters Apr 28 '19 at 14:33

0 Answers0