Arguments for "type metaclass" __init__ method

Chris Angelico rosuav at gmail.com
Mon Jun 22 10:54:27 EDT 2015


On Mon, Jun 22, 2015 at 1:17 AM, Kaviraj Kanagaraj
<kaviraj at launchyard.com> wrote:
> To dynamically create a class:
> DynamicClass = type("DynamicClass", (object,), {'eggs' : 'spams'})
>
> which means type's __init__ method accepts ClassName, bases(tuple) and
> attrbs(dict) as args.
>
>
> But in case of creating class via class definition("type" act as default
> metaclass), the type is called by following syntax,
>
> type(cls, classname, bases, attrbs)
>
> My doubt is how it possible to pass "cls" as argument(as class is not even
> created before calling meta class). Also how "type" is accepting different
> args in two different cases?

If you're looking at the parameters to __init__, it's normal for the
first parameter to be called 'self', and to be the newly-created
object. I suspect that might be what you're seeing here; when you
explicitly call the type, it goes through standard object creation
steps, calling __new__ and (usually) then __init__, resulting in a
call that has the additional argument on it.

So 'cls' is the class that's busily being defined.

ChrisA



More information about the Python-list mailing list