Is it dangeous when using custom metaclass?
jfong at ms4.hinet.net
jfong at ms4.hinet.net
Tue Oct 16 04:45:01 EDT 2018
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__?
> Whether it will cause a problem depends on what StructureMeta's
> __init__ is supposed to do. Presumably you want a given structure
> class to start allocating its offsets where its base class left
> off, in which case you may need to do something like this:
>
> class StructureMeta(type):
> def __init__(self, clsname, bases, clsdict):
> if bases:
> offset = bases[0].offset # assuming there isn't more than one base
> else:
> offset = 0
> ...
>
> (BTW, why do you use setattr() to set the offset attribute
> instead of just doing self.offset = offset?)
No particular reason, just follows the same code pattern ahead of it where the attribute names are from a list:-)
--Jach
More information about the Python-list
mailing list