Python 与 meta programming

meta programming: 编写能改变语言语法特性或者运行时特性的程序


Meta- 这个前缀在希腊语中的本意是「在…后,越过…的」,类似于拉丁语的 post-,比如 metaphysics 就是「在物理学之后」,这个词
最开始指一些亚里士多德的著作,因为它们通常排序在《物理学》之后。

但西方哲学界在几千年中渐渐赋予该词缀一种全新的意义:关于某事自身的某事。比如 meta-knowledge 就是「关于知识本身的知识」,
meta-data 就是「关于数据的数据」,meta-language 就是「关于语言的语言」,而 meta-programming 也是由此而来,是「关于编程的编程」。

弄清了词源和字面意思,可知大陆将 meta- 这个前缀译为「元」并不恰当。台湾译为「后设」,稍微好一点点,但仍旧无法望文生义。
也许「自相关」是个不错的选择,「自相关数据」、「自相关语言」、「自相关编程」——但是好像又太罗嗦了。

 

Meta programming is the writing of computer programs that write or manipulate other programs (or themselves) as their data, 

or that do part of the work at compile time that would otherwise be done at runtime. In some cases, this allows programmers to

minimize the number of lines of code to express a solution (hence reducing development time), or it gives programs greater

flexibility to efficiently handle new situations without recompilation.

 

>>> class A(object):
    def __init__(self):
        self.a = "hello"

        
>>> class B(object):
    def __init__(self):
        self.a = "world"

        
>>> def change_a():
    b = B()
    b.a = "!"
    return b
>>> callables = [A, B, change_a]
>>> print [x().a for x in callables]
['hello', 'world', '!']

 

ruby

>> ruby has no bare words
NameError: undefined local variable or method `words' for main:Object
        from (irb) 1
>> def method_missing(*args); args.join(" "); end
=> nil
>> ruby has bare words
=> "ruby has bare words"
>> bare words can even have bangs!
=> "bare words can even have bangs!"

C、C++、Python、JavaScript…… 多数流行的语言或多或少都有元编程能力;Lisp 诸方言更是以元编程为基本。而 Ruby 更是因为元
编程易用又强大,被许多人拿来写 DSL,因为元编程可以捏出「本不存在的语法特性」来让书写 DSL 变得简单。
posted @ 2015-03-08 17:43  等风来。。  Views(567)  Comments(0Edit  收藏  举报
------------------------------------------------------------------------------------------------------------ --------------- 欢迎联系 x.guan.ling@gmail.com--------------- ------------------------------------------------------------------------------------------------------------