As I read in documentation I can create class dynamically but how to replace this class metaclass?
Should I just replace type metaclass with SomeMetaClass?
The question is very simple but simple help will be welcome too.
As I read in documentation I can create class dynamically but how to replace this class metaclass?
Should I just replace type metaclass with SomeMetaClass?
The question is very simple but simple help will be welcome too.
As I see, you want to change the metaclass after class creation. If so, you can achieve it in the same way that you can change the class of an object. For starters, the initial metaclass needs to be different from type, the __init__ and __new__ of the new metaclass won't be called (though you can manually call __init__ or a method that performs __init__'s job).
NewClass = SomeMetaClass.__new__('NewClass', (object, ), {})
The __new__ method is something similar to __init__ and gets called prior to __init__. It will be clear with the following example:
In [1]: class Foo(object):
def __new__(cls, *args, **kwargs):
print 'inside __new__'
return super(Foo, cls).__new__(cls, *args, **kwargs)
def __init__(self, *args, **kwargs):
print 'inside __init__'
In [2]: f = Foo()
inside __new__
inside __init__
Execution sequence when f = Foo() is called is as follows:
Foo.__new__() gets called __super____new__ method of object is called, and the class is instantiated. __init__ method of Foo is called.Check this for more info.
Hope that helps.
SomeMetaclass metaclass instead type metaclass - whatever thank for suggestions.
SomeMetaclass.__new__("name", (object,), {})?type.