##language:zh #pragma section-numbers off ##含有章节索引导航的 ZPyUG 文章通用模板 <> ## 默许导航,请保留 <> = Quine~打印自个儿 = ##startInc == 题面儿 == {{{ Hanfei reply-to python-cn@googlegroups.com to python-cn`CPyUG`华蟒用户组 date Mon, Jan 26, 2009 at 22:49 subject [CPyUG:77731] 过年了,给大家出个题拜年! }}} 你能不能写出一段程序,你一执行它,它就把自己的源代码原封不动地打印在屏幕上?注意,这个程序不能使用任何外部文件! --~ === 参考 === http://en.wikipedia.org/wiki/Quine_(computing) === shell909090 === 哈哈,看来原版代码,简短多了。 {{{#!python a="a=%s%s%s;print a%%(chr(34),a,chr(34));";print a%(chr(34),a,chr(34)); }}} 昨天实验了一些有意思的方法,例如挂钩compile函数,然后想法触发reload自 身。想法中,此时python应当为我们读好数据,我们只要显示就对了。但是实际 上,`__main__`无法re-init,而且即使reload也不会触发compile函数。 虽然这个没成功,不过又实验出一个方法。 {{{ a=['print "a="+str(a)','for i in a:','\tprint i'] print "a="+str(a) for i in a: print i }}} === The Quine Page (self-reproducing code) === http://www.nyx.net/~gthompso/quine.htm ==== Frank Stajano (fstajano@orl.co.uk) ==== {{{#!python l='l=%s;print l%%`l`';print l%`l` }}} ==== Greg Stein (gstein@microsoft.com) ==== {{{#!python x='x=%s\012print x%%`x`' print x%`x` }}} ==== Joseph DeVincentis . ==== {{{#!python q='"' q1="'" n='\n' s='\\' r1="def f(a,s1,s2,s3,s4):" r2=" print a+'1='+q+s1+q+n+a+'2='+q+s2+q" r3=" print a+'3='+q+s3+q+n+a+'4='+q+s4+q" r4=" print s1+n+s2+n+s3+n+s4" def f(a,s1,s2,s3,s4): print a+'1='+q+s1+q+n+a+'2='+q+s2+q print a+'3='+q+s3+q+n+a+'4='+q+s4+q print s1+n+s2+n+s3+n+s4 p1="print 'q='+q1+q+q1+n+'q1='+q+q1+q" p2="print 'n='+q1+s+'n'+q1+n+'s='+q1+s+s+q1" p3="f('r',r1,r2,r3,r4)" p4="f('p',p1,p2,p3,p4)" print 'q='+q1+q+q1+n+'q1='+q+q1+q print 'n='+q1+s+'n'+q1+n+'s='+q1+s+s+q1 f('r',r1,r2,r3,r4) f('p',p1,p2,p3,p4) }}} ==== Terry Reedy (tjreedy@udel.edu) ==== Note: works as a command line input string {{{#!python import sys;f=sys.stdout; x='import sys;f=sys.stdout;x=%s;f.write(x%%`x`)';f.write(x%`x`) }}} ==== Terry Reedy (tjreedy@udel.edu) ==== Note: works as an interactive string input. The double quotes could theoretically be removed. {{{#!python "x='x=%s;x%%`x`';x%`x`" }}} ==== Omar Antolin (omar@galois.fciencias.unam.mx) ==== {{{#!python a = ['print "a =", a', 'for s in a: print s'] print "a =", a for s in a: print s }}} ==== Magnus Lie Hetland ==== Note: bash command line that runs a Python command {{{#!python python -c "x='python -c %sx=%s; print x%%(chr(34),repr(x),chr(34))%s'; print x%(chr(34),repr(x),chr(34))" }}} ##endInc ---- '''反馈''' 创建 by -- ZoomQuiet [<>]