huh… metaclass, isn’t it the singleton class in ruby?
Just feel more and more the same for Ruby and Python in the class of class, everything is an object, etc.
In python 2
class Foo(Bar): pass
Python will look for metaclass in the class definition. If it finds it, it will use it to create the object class Foo. If it doesn’t, it will use type to create the class.
- Is there a metaclass attribute in Foo?
- If yes, create in-memory a class object (I said a class object, stay with me here), with the name Foo by using what is in metaclass.
- If Python can’t find metaclass, it will look for a metaclass at the MODULE level, and try to do the same (but only for classes that don’t inherit anything, basically old-style classes).
- Then if it can’t find any metaclass at all, it will use the Bar’s (the first parent) own metaclass (which might be the default type) to create the class object.
Be careful here that the metaclass attribute will not be inherited, the metaclass of the parent (Bar.class) will be. If Bar used a metaclass attribute that created Bar with type() (and not type.new()), the subclasses will not inherit that behavior.
Metaclasses in Python 3
The syntax to set the metaclass has been changed in Python 3:
class Foo(object, metaclass=something, kwarg1=value1, kwarg2=value2): ...