metaclass_example_3.py

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


from pprint import *

def eval_print(expr, _locals=None, _globals=None):
  print "%s = %s" % (expr, eval(expr, _locals, _globals))

class Foo(object):
  pass

class ChattyType(type):
    def __new__(cls, name, bases, dct):
        print "ChattyType.__new__(%s): Allocating memory for class %s with bases %s and dct %s" % (cls, name, bases, pformat(dct))
        dct['_a'] = 100
        result = type.__new__(cls, name, bases, dct)
        print "ChattyType.__new__: Returning", result
        eval_print("isinstance(result, ChattyType)", locals(), globals())
        return result

    def __init__(cls, name, bases, dct):
        print "ChattyType.__init__(self/cls=%s): Init'ing (configuring) class %s with bases %s and dct %s" % (cls, name, bases, pformat(dct))
        dct['b'] = 2
        super(ChattyType, cls).__init__(name, bases, dct)

    def ck_foo(cls, x):
        print "ChattyType:ck_foo(self=%s) with x = %s" % (cls, x)

class C(object):
  __metaclass__ = ChattyType
  def __init__(self, something):
    print "C inited with something =", something
    self.something = something
    super(C, self).__init__()

  def ck_foo(self, x):
      print "C:ck_foo(self=%s) with x = %s" % (self, x)