- 论坛徽章:
- 0
|
本帖最后由 杨奇龙 于 2011-07-24 11:45 编辑
当使用 self 来调用变量population的时候,此变量是属于实例的。当 Jack 构造完成,结束howmany()函数结束时Jack 实例的population 就注销了,而Tom 的population 变量还是存在的,- #!/etc/bin/python
- # Filename: objvar.py
- class Person:
- '''Represents a person.'''
- population = 0
- def __init__(self, name):
- '''Initializes the person's data.'''
- self.name = name
- #!/etc/bin/python
- # Filename: objvar.py
- 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
- [b] self.population += 1[/b]
- def __del__(self):
- '''I am dying.'''
- print '%s is dying ' %self.name
- print '%s says bye.' % self.name
- [b]self.population -= 1[/b]
- if self.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 self.population == 1:
- print 'I am the only person here.'
- else:
- print 'We have %d persons here.' % Person.population
- Jack = Person('Jack')
- Jack.sayHi()
- Jack.howMany()
- Tom = Person('Tom')
- Tom.sayHi()
- Tom.howMany()
- print '\n Jack.population ',Jack.population
- print '\n Tom.population =',Tom.population
- #Jcak.sayHi()
- #Jack.howMany()
- "objvar.py" 56L, 1287C written
- [yang@rac1 python]$ python objvar.py
- (Initializing Jack)
- Hi, my name is Jack.
- I am the only person here.
- (Initializing Tom)
- Hi, my name is Tom.
- I am the only person here.
- Jack.population 1
- Tom.population = 1
- Jack is dying
- Jack says bye.
- I am the last one.
- Tom is dying
- Tom says bye.
- I am the last one.
复制代码 然后看看下面的帖子: |
|