What use of these _ prefix members?

Jason Swails jason.swails at gmail.com
Tue Jan 12 10:01:57 EST 2016


On Tue, Jan 12, 2016 at 9:12 AM, me <self at example.org> wrote:

> On 2016-01-10, Peter Otten <__peter__ at web.de> wrote:
> >>>> class Derived(Base):
> > ...     def _init(self, x):
> > ...         super()._init(x)
> > ...         print("do something else with", x)
> > ...
> >>>> Derived(42)
> > do something with 42
> > do something else with 42
> ><__main__.Derived object at 0x7f8e6b3e9b70>
> >
>
> I think you are doing inheritance wrong.
>

​There's nothing "wrong" about this, and there are times this type of
pattern is justified.  Sure, *this* example doesn't make sense to do it
this way, but this is just an illustrative example.  I would even call this
type of pattern pythonic.
​
​

> AFAIK you should call directly the __init__() of the parent class, and
> ​​
> pass *args and **kwargs instead.
>

Sometimes there's no need to call __init__ on the parent class directly,
and the base class's __init__ is sufficient for the derived class.  And
perhaps initialization requires numerous "steps" that are easiest to grok
when split out into different, private sub-methods. For example:

class Derived(Base):
​    def __init__(self, arg1, arg2, arg3):
        self._initial_object_setup()
        self._process_arg1(arg1)
        self._process_arg23(arg2, arg3)
        self._postprocess_new_object()​

This makes it clear what is involved in the initialization of the new
object.  And it allows the functionality to be split up into more atomic
units.  It also has the added benefit of subclasses being able to more
selectively override base class functionality.  Suppose Derived only needs
to change how it reacts to arg1 -- all Derived needs to implement directly
is _process_arg1.  This reduces code duplication and improves
maintainability, and is a pattern I've used myself and like enough to use
again (not necessarily in __init__, but outside of being automatically
called during construction I don't see anything else inherently "specialer"
about __init__ than any other method).

All the best,
Jason



More information about the Python-list mailing list