Is it dangeous when using custom metaclass?
Gregory Ewing
greg.ewing at canterbury.ac.nz
Tue Oct 16 02:00:45 EDT 2018
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.
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?)
--
Greg
More information about the Python-list
mailing list