看了一篇文章,里面提到一个python初始化对象及释放对象的顺序问题,其人测试的饶有兴致,我看了看,发现是随机释放顺序,虽然没什么用,但是挺有意思的。
最近在学习python,看的是《简明python教程》,写的很是通俗易懂。
在一个类和对象的变量的例子中,看到代码运行结果突然想到在python中对象的生命周期的问题,代码运行结果:
#
!/usr/bin/env python
# coding=utf-8
# filename :objvar.py
class Person:
population = 0
def __init__ (self,name):
self.name = name
print ( " initializing %s " % self.name)
Person.population += 1
def __del__ (self):
print ( " %s say bye " % self.name)
Person.population -= 1
if Person.population == 0 :
print ( " I'm the last one " )
else :
print ( " There are still %d person left " % Person.population)
def SayHi(self):
print ( " Hi,my name is %s " % self.name)
def HowMany(self):
if Person.population == 1 :
print ( " I am the only Person here " )
else :
print ( " We have %d person here " % Person.population)
swaroop = Person( " Swaroop " ) # initializing Swaroop
swaroop.SayHi() # Hi,my name is Swaroop
swaroop.HowMany() # I am the only Person here
kalam = Person( " Kalam " ) # initializing Kalam
kalam.SayHi() # Hi,my name is Kalam
kalam.HowMany() # We have 2 person here
swaroop.SayHi() # Hi,my name is Swaroop
swaroop.HowMany() #
# coding=utf-8
# filename :objvar.py
class Person:
population = 0
def __init__ (self,name):
self.name = name
print ( " initializing %s " % self.name)
Person.population += 1
def __del__ (self):
print ( " %s say bye " % self.name)
Person.population -= 1
if Person.population == 0 :
print ( " I'm the last one " )
else :
print ( " There are still %d person left " % Person.population)
def SayHi(self):
print ( " Hi,my name is %s " % self.name)
def HowMany(self):
if Person.population == 1 :
print ( " I am the only Person here " )
else :
print ( " We have %d person here " % Person.population)
swaroop = Person( " Swaroop " ) # initializing Swaroop
swaroop.SayHi() # Hi,my name is Swaroop
swaroop.HowMany() # I am the only Person here
kalam = Person( " Kalam " ) # initializing Kalam
kalam.SayHi() # Hi,my name is Kalam
kalam.HowMany() # We have 2 person here
swaroop.SayHi() # Hi,my name is Swaroop
swaroop.HowMany() #