Is it dangeous when using custom metaclass?

jfong at ms4.hinet.net jfong at ms4.hinet.net
Wed Oct 17 04:17:56 EDT 2018


dieter at 2018/10/17 UTC+8 PM 1:15:01 wrote:
> jfong at ms4.hinet.net writes:
> > Gregory Ewing at 2018/10/16 UTC+8 PM 2:01:01 wrote
> >> jfong at ms4.hinet.net wrote:
> >> > class Structure(metaclass=StructureMeta): ...
> >> > 
> >> > class PolyHeader(Structure): ...
> >> > 
> >> > As my understanding, the metaclass's __init__ was called when a class was
> >> > created. In the above example, both the Structure and PolyHeader called it.
> >> > My question is: because the PolyHeader inherited Structure, is it reasonable
> >> > for PolyHeader to call this __init__ again? Will it cause any possible
> >> > trouble?
> >> 
> >> It's reasonable for both to call it, because they're distinct
> >> instances of StructureMeta, each of which need to be initialised.
> >
> > The PolyHeader is already initialized by inheritance. Is there any way to bypass this __init__?
> 
> If there were any, you should find it described in metaclass related documentation.
> 
> Likely, you can ensure that followup calls of "__init__" effectively
> behave as "no-op"s: let the first call place a marker in the initialized
> object and check in later calls whether it is already there.

Hard to find the document of type.__init__. I can only guess it does nothing, at least no thing serious, to avoid trouble the metaclass's __init__ may cause in a class hierarchy:-)



More information about the Python-list mailing list