I know that checking types in Python is bad and you should probably never do it. But I can’t seem to find the disadvantage to this.
class O(object):
def __init__(self, name):
'''Can only be called in derived classes.'''
if type(self) is O:
message = "%(class)s cannot be instantiated, it must be derived."
raise TypeError, message % { "class" : O }
self.name = name
def fn(self):
'''Must be populated in derived classes.'''
raise NotImplementedError
Now if someone tries to instantiate O, a class I never meant to be instantiated, they know immediately.
Is this still bad form?
Look at Abstract Base Classes as they will provide more fine grained control over how the subclasses are instantiated if this is something that you really want to do.
All in all, this might be a valid use because you are not preventing me from passing whatever I want to your code but I still wouldn’t consider it pythonic. You are telling me that I can’t instantiate your class. What If I want to?
Using ABC’s, it looks like:
This has the advantage of not breaking super on the
fnmethod. As you have it with theraise NotImplementedError, you are breaking super for multiple inheritance. If a class derives from two classes that subclassOand both call super (as they should to allow for multiple inheritance) then it will create the exception that you raise.So now, you are not just telling me that I can’t instantiate your class, you are telling me that I can’t use multiple inheritance when subclassing from your class.