Metaclasses - magic functions

Ian Kelly ian.g.kelly at gmail.com
Fri Dec 23 09:14:43 EST 2016


On Fri, Dec 23, 2016 at 5:14 AM, Mr. Wrobel <mr at e-wrobel.pl> wrote:
> Hi,thanx for answers, let's imagine that we want to add one class attribute
> for newly created classess with using __init__ in metaclass, here's an
> example:
>
> #!/usr/bin/env python
>
> class MetaClass(type):
>     # __init__ manipulation:
>
>     def __init__(cls, name, bases, dct):
>         dct['added_in_init'] = 'test'
>         super(MetaClass, cls).__init__(name, bases, dct)
>
> class BaseClass(object):
>     __metaclass__ = MetaClass
>
> class NewBaseClass(BaseClass):
>     pass
>
> print("Lets print attributes added in __init__ in base classes:")
>
> print(BaseClass.added_in_init)
>
> print(NewBaseClass.added_in_init)
>
> after running it: AttributeError: type object 'BaseClass' has no attribute
> 'added_in_init'
>
> Adding the same in __new__ works. Can anyone explain me please what's wrong?

When __init__ is called, the class has already been constructed by
__new__, and the 'dct' argument has already been copied into the class
dict. The base __init__ method does nothing, so adding the item to dct
and calling up doesn't accomplish anything.

Instead, the 'cls' argument that gets passed into __init__ is the
newly constructed class, so just use that to set the attributes:

    cls.added_in_init = 'test'


More information about the Python-list mailing list