Tutorial by Examples

When type is called with three arguments it behaves as the (meta)class it is, and creates a new instance, ie. it produces a new class/type. Dummy = type('OtherDummy', (), dict(x=1)) Dummy.__class__ # <type 'type'> Dummy().__class__.__class__ # <type 'type'> It is po...
A singleton is a pattern that restricts the instantiation of a class to one instance/object. For more info on python singleton design patterns, see here. class SingletonType(type): def __call__(cls, *args, **kwargs): try: return cls.__instance except AttributeErr...
Metaclass syntax Python 2.x2.7 class MyClass(object): __metaclass__ = SomeMetaclass Python 3.x3.0 class MyClass(metaclass=SomeMetaclass): pass Python 2 and 3 compatibility with six import six class MyClass(six.with_metaclass(SomeMetaclass)): pass
Functionality in metaclasses can be changed so that whenever a class is built, a string is printed to standard output, or an exception is thrown. This metaclass will print the name of the class being built. class VerboseMetaclass(type): def __new__(cls, class_name, class_parents, class_dict)...
What is a metaclass? In Python, everything is an object: integers, strings, lists, even functions and classes themselves are objects. And every object is an instance of a class. To check the class of an object x, one can call type(x), so: >>> type(5) <type 'int'> >>> typ...
You may have heard that everything in Python is an object. It is true, and all objects have a class: >>> type(1) int The literal 1 is an instance of int. Lets declare a class: >>> class Foo(object): ... pass ... Now lets instantiate it: >>> bar = Foo() Wh...

Page 1 of 1