以教程中的一段小诗开始:
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之路吧