0

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.

2
  • 2
    SomeMetaclass.__new__("name", (object,), {}) ? Commented Jul 31, 2014 at 0:27
  • 1
    Yes, just use the name of your metaclass instead of type. Commented Jul 31, 2014 at 0:28

1 Answer 1

1

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
  • It calls its parent's new method using __super__
  • finally the __new__ method of object is called, and the class is instantiated.
  • Finally the __init__ method of Foo is called.

Check this for more info.

Hope that helps.

Sign up to request clarification or add additional context in comments.

1 Comment

It looks I need to use SomeMetaclass metaclass instead type metaclass - whatever thank for suggestions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.