Metaclass

http://eli.thegreenplace.net/2011/08/14/python-metaclasses-by-example/
http://eli.thegreenplace.net/2012/04/16/python-object-creation-sequence/

class Foo:
  pass
 
class Foo2(object)
  pass
 
print type(Foo)
print type(Foo2)

the 1st print is classobj, the 2nd print is type

the difference between Foo and Foo2 is Foo2 is derived from object.

In 2.x, the default metaclass is actually ‘classobj’, which implements old-style class semantics. You have to either inherit from object, invoke type explicitly or set your metaclass to type in order to get a full fledged new style class.

The process to create a class

but what Python does under the hood is the following:

  • When it sees a class definition, Python executes it to collect the attributes (including methods) into a dictionary.
  • When the class definition is over, Python determines the metaclass of the class. Let’s call it Meta. if the class or any bases has a metaclass defined, python use it, otherwise Meta = type.
  • Eventually, Python executes Meta(name, bases, dct), where:
    • Meta is the metaclass, so this invocation is instantiating it.
    • name is the name of the newly created class
    • bases is a tuple of the class’s base classes
    • dct maps attribute names to objects, listing all of the class’s attributes

meta class from type

def make_myklass(**kwattrs):
   return type('MyKlass', (object,), dict(**kwattrs))
 
myklass_foo_bar = make_myklass(foo=2, bar=4)

is equal to the following:

class MyKlass(object):
  foo = 2
  bar = 4

funcking complicated

http://stackoverflow.com/questions/395982/metaclass-new-cls-and-super-can-someone-explain-the-mechanism-ex

for new and init in regular class

Use new when you need to control the creation of a new instance. Use init when you need to control initialization of a new instance.

new is the first step of instance creation. It's called first, and is responsible for returning a new instance of your class. In contrast, init doesn't return anything; it's only responsible for initializing the instance after it's been created.

In general, you shouldn't need to override new unless you're subclassing an immutable type like str, int, unicode or tuple.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License