7

Based on my limited Python knowledge Metaclass is another class. In the following example I am just building a metaclass. Here I overloaded the __new__ method. My expectation is at the end of the class declaration when type.__new__() is called it will be delegated to MyMeta.__new__(). But that never happens.

print('Building MetaOne')

class MyMeta(type):
      def __new__(meta, classname, supers, classdict):
          print('In MyMeta:', classname)

      def myfunc(self):
          print ('In myfunc')

Here from MyMeta's __new__() I don't see the print.

But on the contrary if I now use MyMeta class as a meta class to another class like:

print('Building Another class')
class Super(metaclass = MyMeta):
      def myfunc(self):
          print ('In Super myfunc')

At the end of this class I see MyMeta's __new__ is getting invoked.

Can some one please help me understand why this happens?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
py2016
  • 71
  • 3
  • 1
    No, `__new__` is not called when you created the meta class; . `Super` is an *instance* of the metatype, a class object, so then `__new__` is called to create it. Note that your `__new__` method returns `None`, rather than a new class object. You may want to add `return super().__new__(meta, classname, supers, classdict)` to the end of it. – Martijn Pieters Dec 26 '17 at 23:39
  • You can use `__new__` on a class definition as well, and it would only be called when you call the class to create new instances. – Martijn Pieters Dec 26 '17 at 23:39
  • Thanks Martin. Is this because when I create class object MyMeta (or any other class object), only the \__new()__ function of it's metaclass or metaclass of the base classes get called ? – py2016 Dec 26 '17 at 23:49
  • exactly, which is `type()`. You can't create meta metaclasses. – Martijn Pieters Dec 27 '17 at 00:17

0 Answers0