Can you force derived class from a bass class to define specific member variables in python?

30 Views Asked by At

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()?

1

There are 1 best solutions below

0
Barmar On

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')