From Python
Metaprogramming in
If the class is the template of the object instance, the Meta class is the class template and the class factory.
Listing 1.
Old Python 1.5.2
Factory
Python 1.5.2 (#0, Jun 27 1999, 11:23:01) [...]
Copyright 1991-1995 Stichting mathematisch Centrum, Amsterdam
>>> Def class_with_method (func ):
... Class Klass: Pass
... Setattr (Klass, func. _ name __, func)
... Return Klass
...
>>> Def say_foo (Self): Print 'foo'
...
>>> Foo = class_with_method (say_foo)
>>> Foo = Foo ()
>>> Foo. say_foo ()
Foo
Factory function class_with_method ()
Dynamically create a class and return the class, which contains the methods/functions passed to the factory. Operate the class itself in the function body before returning the class. New
The module provides a more concise encoding method, but the options are different from those of the custom code in the class factory. For example:
Listing 2. New
Class factory in the module
>>> From new import classobj
>>> Foo2 = classobj ('foo2', (Foo,), {'bar': Lambda self: 'bar '})
>>> Foo2 (). Bar ()
'Bar'
>>> Foo2 (). say_foo ()
Foo
Magic of metadata
Listing 3.
Type of the class factory metadata
>>> X = type ('x', (), {'foo': Lambda self: 'foo '})
>>> X, x (). Foo ()
(<Class '_ main _. X'>, 'foo ')
Listing 4.
As the type of the class factory
Descendant
>>> Class chattytype (type ):
... Def _ new _ (CLS, name, bases, DCT ):
... Print "allocating memory for Class", name
... Return type. _ new _ (CLS, name, bases, DCT)
... Def _ init _ (CLS, name, bases, DCT ):
... Print "init 'ing (grouping) Class", name
... Super (chattytype, CLS). _ init _ (name, bases, DCT)
...
>>> X = chattytype ('x', (), {'foo': Lambda self: 'foo '})
Allocating memory for Class X
Init 'ing (grouping) Class X
>>> X, x (). Foo ()
(<Class '_ main _. X'>, 'foo ')
Listing 5.
Attaches the class method to the generated class.
>>> Class printable (type ):
... Def whoami (CLS): Print "I am a", CLS. _ name __
...
>>> Foo = printable ('foo ',(),{})
>>> Foo. whoami ()
I am a foo
>>> Printable. whoami ()
Traceback (most recent call last ):
Typeerror: unbound method whoami () [...]
Listing 6.
Set metadatabase with class attributes
>>> Class bar:
... _ Metaclass _ = printable
... Def foomethod (Self): Print 'foo'
...
>>> Bar. whoami ()
I am a bar
>>> Bar (). foomethod ()
Foo
Refer:
Python
Metaprogramming in
Python
Metaprogramming in 2nd
Part
Python
Metaprogramming in 3rd
Part