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
>>>
相关文档:
关于C++和Python之间互相调用的问题,可以查找到很多资料。本文将主要从解决实际问题的角度看如何构建一个Python和C++混合系统。
&nbs ......
# 004
# 利用三引号(''' or """)可以指示多行字符串
print '''line1
line2
line3'''
# 另外,你还可以在三引号中任意使用单引号和双引号
print ''' "What's up? ," he replied.'''
# 否则,你好使用转义符来实现同样的效果
# 还是使用三引号好,不然就破坏了视觉美了
print ' \"Wha ......
源代码下载:下载地址在这里
# 026
aList = ['1','2','3','4']
aListCopy = aList # 其实,这里仅仅复制了一个引用
del aList[0]
print aList
print aListCopy # 两个引用指向了了同一个对象,所以打印结果一样
aListCopy = aList[:] # 这是复制整个对象的有效方法
del aList[0]
print aList
print aListCopy
......
源代码下载:下载地址在这里
# 028
consoleInput = raw_input('请输入点什么吧:')
aFile = file(r'C:\out.txt', 'w')
aFile.write(consoleInput + '\n')
aFile.write('这里是第二行')
aFile.close()
output:
>>>
请输入点什么吧:haha
>>>
......
源代码下载:下载地址在这里
# 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.nam ......