0

If I have a class say:

class BaseClassOnly():
    def __init__(self):
        self._foo = None

    def do_stuff(self):
        print("doing stuff with foo" + self._foo)

I want to force all classes derived from BaseClassOnly to provide a value for 'self._foo' so that the inherited function do_stuff() will be able to use it. Is there a way to ensure if a class that inherits from BaseClassOnly with result in an error if the variable self._foo is not set in init()?

  • 2
    I think it would be hard to do because there would be no way without introspection of the class `__init__` code. Much easier to force people to implement a method or `property`, then it's trivial without getting into too much black magic – juanpa.arrivillaga May 02 '23 at 18:46
  • 1
    But in general, you would simply document this for the consumers of the class – juanpa.arrivillaga May 02 '23 at 18:47
  • abstract base classes can force subclasses to implement a method. This is typically considered cleaner than forcing subclassees to implement a field. – Frank Yellin May 02 '23 at 18:47

1 Answers1

0

If you assume that the child classes will call the base class's __init__(), you could use hasattr() to check.

class BaseClassOnly():
    def __init__(self):
        if not hasattr(self, '_foo'):
            raise ValueError('self._foo must be defined')
Barmar
  • 741,623
  • 53
  • 500
  • 612