'Limit access to a class function to child classes that inherit from the class
I have a use case where there are some attributes that are common to different categories that I capture through a base class and then there are some category specific parameters that are assigned in the child class definitions. For example,
class Parent:
def __init__(self):
self.category_param = None
def run_category(self):
self.category_param.run()
class Child(Parent):
def __init__(self, cat_param):
super(Child, self).__init__()
self.category_param = cat_param
Although the function run_category has the same form for all instantiations of class Child, it does use a category specific param that is None/undefined in class Parent.
I am looking for a clean way to prevent being able to call run_category() from an instantiation of class Parent.
parent = Parent()
parent.run() # Should throw an error
I would like the above code to throw an error message that I have control over (since the error message None has no attribute run() is undesirable and would be the current way the above code crashes).
A possibility is of course to define run_category as,
def run_category(self):
if self.category_param is not None:
self.category_param.run()
else:
raise NotImplementedError("method run() is not available for abstract base class Parent")
but I was looking for something cleaner/more pythonic.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
