metaclass_example_2.py

Send to Kindle
home » snippets » python » metaclass » metaclass_example_2.py


from pprint import *

# MC is inheriting from object here and not from type
class MC(object):
  def __new__(cls, *args):
    print "__new__ called for class %s with args %s" % (cls, args)
    result = type(*args)
    print "__new__ returning", result
    return result
  def __init__(self, *args):
    print "__init__ called for self %s with args %s" % (self, args)
    return super(C, self).__init__()

class C(object):
  __metaclass__ = MC
  a = 1

# This example does nothing different than example 1 which just uses
# a function.  The cls to MC.__new__is MC and the args are the 3-tuple passed
# to type(...).  The MC.__init__ is never called because __new__ returns
# a C and not an MC.