易截截图软件、单文件、免安装、纯绿色、仅160KB

Python入门的36个例子 之 31

源代码下载:下载地址在这里
# 035
class Person:
population = 0 #这个变量是属于整个类的
def __init__(self, name):
self.name = name
print '初始化 %s' % self.name
Person.population += 1
# end of def
def __del__(self):
print '%s says bye.' % self.name
Person.population -= 1
if Person.population == 0:
print '我是最后一个人了!'
else:
print '还有%d个人。' % Person.population
# end of if
# end of def
def sayHi(self):
print 'Hi, my name is %s' % self.name
# end of def
def howMany(self):
print Person.population
# end of def
# enf of class
ning = Person('Ning')
ning.sayHi()
ning.howMany()
#zhang = Person('Zhang')
#zhang.sayHi()
#zhang.howMany()
#ning.sayHi()
#ning.howMany()

output:
注意!下面是两次运行的结果,可以看出del(析构函数)的运行时间是不确定的。这个现象的原因在于Python的垃圾回收机制的自动回收时间是不确定的。
初始化 Ning
Hi, my name is Ning
1
>>>
初始化 Ning
Ning says bye.
我是最后一个人了!
Hi, my name is Ning
0
>>>


相关文档:

Python入门的36个例子 之 18

例1:
# _018
# This is a module (if write Chinese in a module, there will be a error)
def func1():
print 'This is function 1.'
def func2():
print 'This is function 2.'
def func3():
print 'This is function 3.'
# 019
# 使用“import”语句调用模块:
import _018_Module
_ ......

Python入门的36个例子 之 19

源代码下载:下载地址在这里
# 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 ......

Python入门的36个例子 之 21

源代码下载:下载地址在这里
# 024
dict1 = {
'5064001':'Mememe',
'5064002':'tutu',
'5064003':'thrthr',
'5064004':'fofo'
}
print dict1['5064003']
# 也可以使用整型作为唯一的编号
dict2 = {
5064001:'Mememe',
506400 ......

Python入门的36个例子 之 27

源代码下载:下载地址在这里
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 ......

Python入门的36个例子 之 28

源代码下载:下载地址在这里
# 032
# 其实cPickle这个模块起到的作用可以用“完美地协调了文件中的内容(对象)和代码中的引用”来形容
import cPickle as p # 这条语句给cPickle起了个小名p
objectFileName = r'C:\Data.txt'
aList = [1, 2, 3]
f = file(objectFileName, 'w')
p.dump(aList, f)
f.close ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号