pythonpython-3.xoopmetaclass

How can I refer to this metaclass inside a metaclass without specifying its name in the code?


I have some python code:

class Meta(type):
    def __new__(cls, name, base, attrs):
        attrs.update({'name': '', 'email': ''})
        return super().__new__(cls, name, base, attrs)

    def __init__(cls, name, base, attrs):
        super().__init__(name, base, attrs)
        cls.__init__ = Meta.func

    def func(self, *args, **kwargs):
        setattr(self, 'LOCAL', True)


class Man(metaclass=Meta):
    login = 'user'
    psw = '12345'

How can I refer to this metaclass inside a metaclass without specifying its name in the code? Without Meta in the row: cls.__init__ = Meta.func

If someone wants to change the name of the metaclass, it will stop working. Because it will be necessary to make changes inside this metaclass. Because I explicitly specified its name in the code. I think this is not right. But I do not know how to express it in another way.

I tried cls.__init__ = cls.func, but it doesn't create local variables for the Man class object. cls refers to the class being created(Man), not the Meta


Solution

  • How can I refer to this metaclass inside a metaclass without specifying its name in the code? Without Meta in the row: cls.init = Meta.func

    You can use the special variable name __class__, like in:

    cls.__init__ = __class__.__init__
    

    Otherwise, the first "cls" parameter in the __init__ method of the metaclass have a reference to the class'class (the metaclass), just as a regular self parameter would:

     cls.__init__ = cls.__class__.__init__
    

    would also work for referencing the function.