以教程中的一段小詩開始:
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
1 #!/usr/bin/env python
2 #coding=utf-8
3 poem = '''\
4 Programming is fun
5 When the work is done
6 if you wanna make your work also fun:
7 use Python!
8 '''
9
10 f = file('c:\\poem.txt','w')
11 f.write(poem)
12 f.close()
哇,下面這段真是解釋性的腳本語言的魅力啊,動態生成語句,然后直接解釋執行,太靈活了
1 #!/usr/bin/env python
2 #coding=utf-8
3 stm = 'a = 10'
4 exec(stm)
5 print a
直接輸出了a的值10
還有,更厲害的是可以給對象動態的添加屬性,不知道這么理解對不對
1 #!/usr/bin/env python
2 #coding=utf-8
3 class Person:
4 def __init__(self, tel, mobile, email, address, **elseInfo):
5 self.tel = tel
6 self.mobile = mobile
7 self.email = email
8 self.address = address
9
10 for key, value in elseInfo.items():
11 stm = "self.%s = \"%s\"" % (key, value)
12 exec(stm)
13
14 loh = Person('2*******3','1368****533','elgnaw(at)tju.edu.cn','Tianjin University',email2 = 'burgundy.loh(at)gmail.com',mobile2 = '136*****211')
15
16 print loh.email
17 print loh.email2
18 print dir(loh)
19
輸出為
elgnaw(at)tju.edu.cn
burgundy.loh(at)gmail.com
['__doc__', '__init__', '__module__', 'address', 'email', 'email2', 'mobile', 'mobile2', 'tel']
這里是python的教程:
簡明 Python 教程
也開始你的python之路吧