Suppose I have a class C
with a method f()
which is meant to be used only within C
's implementation, but which should be overridden by C
's subclasses.
Is it reasonable, or "pythonic", to consider it private, i.e. to name it _f()
rather than f()
?
In other words would you distinguish the interface provided to subclasses from the interface provided to code outside the inheritance hierarchy?
Best Answer
Pythonically speaking, you should utilize the Abstract Base Class module to implement this functionality.
Example:
Then this is what happens when you attempt to instantiate a subclass of
MyBaseClass
without overriding_f()
:Note that there are no programmatically "private" methods in Python. That being said, a single underscore before the name (
_f()
) is used to signify that the method should only be accessed internally.