Say I make a class named Bird which I only want to be used as a parent class and derived classes are expected to have a method flap_wings
:
class Bird:
def fly(self):
self.flap_wings()
An expected derived class might look like:
class Eagle(Bird):
def flap_wings(self):
print('flapping wings')
What is a nice, clear way for Bird
to both assert that its derived classes have the method flap_wings
as well as include documentation on what flap_wings
is expected to do?
Right now, I'm using __init_subclass__
:
class Bird:
def fly(self):
self.flap_wings()
def __init_subclass__(cls, **kwargs):
assert hasattr(cls, 'flap_wings'), (
"Derived classes have to have a flap_wings method which should "
"print 'flapping wings'."
)
But, the assert expression only shows up after you create a Bird class and is not a "real" docstring that can be accessed through help
.
I know this is an open ended question but what are other better ways? It's not against the rules to define flap_wings
within Bird
first, maybe just with the body pass
and a docstring. But I just couldn't find the "standard" ways to handle this situation. So I'm looking for any suggestions.