Reputation: 2442
I've defined a base abstract model class which gives some extra funcionality to the model, like this:
class BaseModel(models.Model):
# ... some fields and methods
class Meta:
abstract = True
class Model1(BaseModel):
# ... some fields and methods
def required_method(self, *args, *kwargs):
# implementation
class Model2(BaseModel):
# ... some fields and methods
Now I need to ensure, that each derived class has number of required methods defined. If any of them is not defined, I need to throw an exception on attempt of execution by manage.py. So in other words, BaseModel should require each derived class to define some interfaces, that this BaseModel uses, but not defines by itself.
Where should I implement this checking? Is the __init__
of the BaseModel
a good place to check this?
Edit: Purpose of this is just for safety. If somebody or me after some time, will try to inherit from BaseModel
class, but forgets to implement required methods, the code will still run until BaseModel
code tries to execute any missing method. So it's potentially dangerous to me. It's better to prevent such code from execution. I believe that Java has such mechanism called interfaces. I'd like to do something similar in Python.
Upvotes: 1
Views: 811
Reputation: 855
Use the decorators in the abc package to mark which methods should be abstract. The package takes care of the checking for you, so you don't even have to worry about a proper location for your checks ;-)
Upvotes: 2