37,720
社区成员
发帖
与我相关
我的任务
分享
class Person:
'''Represents a person.'''
population=0
def __init__(self,name):
'''Initializes the person's data.'''
self.name=name
print '(Initializing %s)' % self.name
# When this person is created, he/she
# adds to the population
Person.population += 1
def __del__(self):
'''I am dying'''
print '%s says bye.' % self.name
Person.population -= 1
if Person.population==0:
print 'I am the last one.'
else:
print 'there are still %d people left.' % Person.population
def sayHi(self):
'''Greeting by the person
Really, that's all it does.'''
print 'Hi, my name is %s.' % self.name
def howMany(self):
'''Prints the current population.'''
if Person.population==1:
print 'I am the only person here.'
else:
print 'We have %d persons here.' % Person.population
gerry=Person('Gerry Young')
gerry.sayHi()
gerry.howMany()
>>>
(Initializing Gerry Young)
Hi, my name is Gerry Young.
I am the only person here.
>>>
(Initializing Gerry Young)
Gerry Young says bye.
I am the last one.
Hi, my name is Gerry Young.
We have 0 persons here.
>>>
class Person:
'''Represents a person.'''
population=0
def __init__(self,name):
'''Initializes the person's data.'''
self.name=name
print '(Initializing %s)' % self.name
# When this person is created, he/she
# adds to the population
Person.population += 1
def __del__(self):
'''I am dying'''
print '%s says bye.' % self.name
Person.population -= 1
if Person.population==0:
print 'I am the last one.'
else:
print 'there are still %d people left.' % Person.population
def sayHi(self):
'''Greeting by the person
Really, that's all it does.'''
print 'Hi, my name is %s.' % self.name
def howMany(self):
'''Prints the current population.'''
if Person.population==1:
print 'I am the only person here.'
else:
print 'We have %d persons here.' % Person.population
gerry=Person('Gerry Young')
gerry.sayHi()
gerry.howMany()
w=Person('wcdj')
w.sayHi()
w.howMany()
>>> man = Person('Jacob') # Person('Jacob') 被 man 引用
(Initializing Jacob)
>>> man = Person('Jack') # man 变成别的了, Person('Jacob') 不被需要了
(Initializing Jack)
Jacob says bye.
there are still 1 people left.
>>> man.population
1
>>>