Python入门的36个例子 之 30
源代码下载:下载地址在这里
# 034
class Person:
def __init__(self, name):
self.name = name # 这一句中第一个name是类中包含的域,第二个name是传进来的参数
# end of def
def sayHello(self):
print 'Hello!'
# end of def
# end of class
p = Person('Ning')
print p.name
p.sayHello()
output:
Ning
Hello!
相关文档:
Python代码优化--少打字小技巧
说明:增加代码的描述力,可以成倍减少你的LOC,做到简单,并且真切有力
观点:少打字=多思考+少出错,10代码行比50行更能让人明白,以下技巧有助于提高5倍工作效率
1. 交换变量值时避免使用临时变量:(cookbook1.1)
老代码:我们经常很熟练于下面的代码
temp = x
x = y
y = ......
StringIO的行为与file对象非常像,但它不是磁盘上文件,而是一个内存里的“文件”,我们可以将操作磁盘文件那样来操作StringIO。一个简单的例子,让你对StringIO有一个感性的认识: 1 #coding=gbk 2 3 import StringIO, cStringIO, sys 4 5 s ......
# 017
def lifeIsAMirror():
string = raw_input()
if string == 'I love you!':
return 'I love you, too!'
elif string == 'Fuck you!':
return ''
else:
return
# end of def
string = lifeIsAMirror()
if len(string) == 0:
print 'You have nothing.'
else: ......
源代码下载:下载地址在这里
# 022
listNum1 = [1, 3]
listNum2 = [2, 4]
listStr1 = ['a', 'c']
listStr2 = ['b', 'd']
# 列表的合并
list1 = listNum1 + listStr1
for ele in list1:
print ele
print '\n'
# 判断列表中是否包含某元素
print 'b' in list1
print 1 in list1
# 删除某个元素
for ele in ......
源代码下载:下载地址在这里
e.g.1
# 030
aFile = file(r'C:\temp.txt', 'a')
aFile.write('又添加了一行。')
aFile.close()
output:
e.g.2
# 030
aFile = file(r'C:\temp.txt', 'a')
aFile.write('又添加了一行。')
aFile.close()
output:
e.g.3
实现根据原始文件有没有最后一行空行的情况来进行&ldqu ......