What use of these _ prefix members?
Peter Otten
__peter__ at web.de
Tue Jan 12 09:52:18 EST 2016
Someone else posting as "me" 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.
If by "you" you mean "me" -- the above sample is an illustration of the
pattern I expected to see elsewhere in the software Robert was quoting, not
an endorsement. I have now looked into the hmmlearn source, and it turns out
that _init() is invoked by the fit() method rather than the initializer.
But...
> AFAIK you should call directly the __init__() of the parent class, and
> pass *args and **kwargs instead.
you sometimes want to break initialisation or any other method into distinct
steps that don't make sense stand-alone:
class Foo:
def method(...)
self._one(...)
self._two(...)
self._three(...)
That way subclasses have the option to override only _two() instead of
method() and users of Foo won't try to invoke _two(...) on its own.
I think this is a good approach.
What arguments you need to accept and/or pass on is a question that you can
decide depending on the actual use-case. I use
*args, **kwargs
only if function is very generic because it makes code hard to follow.
> Except for that, yes, the _init would be conventionally private. Not
> enforced by name mangling though.
More information about the Python-list
mailing list