Just call the "type" built in using three parameters, like this:
ClassName = type("ClassName", (Base1, Base2,...), classdictionary)
update as stated in the comment bellow this is not the answer to this question at all. I will keep it undeleted, since there are hints some people get here trying to dynamically create classes - which is what the line above does.
To create an object of a class one has a reference too, as put in the accepted answer, one just have to call the class:
instance = ClassObject()
The mechanism for instantiation is thus:
Python does not use the new
keyword some languages use - instead it's data model explains the mechanism used to create an instantance of a class when it is called with the same syntax as any other callable:
Its class' __call__
method is invoked (in the case of a class, its class is the "metaclass" - which is usually the built-in type
). The normal behavior of this call is to invoke the (pseudo) static __new__
method on the class being instantiated, followed by its __init__
. The __new__
method is responsible for allocating memory and such, and normally is done by the __new__
of object
which is the class hierarchy root.
So calling ClassObject()
invokes ClassObject.__class__.call()
(which normally will be type.__call__
) this __call__
method will receive ClassObject itself as the first parameter - a Pure Python implementation would be like this: (the cPython version is of course, done in C, and with lots of extra code for cornercases and optimizations)
class type:
...
def __call__(cls, *args, **kw):
constructor = getattr(cls, "__new__")
instance = constructor(cls) if constructor is object.__new__ else constructor(cls, *args, **kw)
instance.__init__(cls, *args, **kw)
return instance
(I don't recall seeing on the docs the exact justification (or mechanism) for suppressing extra parameters to the root __new__
and passing it to other classes - but it is what happen "in real life" - if object.__new__
is called with any extra parameters it raises a type error - however, any custom implementation of a __new__
will get the extra parameters normally)