|
#!/usr/bin/env python
# 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 says bye.' % self.name
Person.population -= 1
if Person.population == 0:
print 'I am the last one.'
else:
print 'There are still %d people here' % 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 persons here.' % Person.population
swaroop = Person('Swaroop')
swaroop.sayHi()
swaroop.howMany()
jack = Person('Jack')
jack.sayHi()
jack.howMany()
swaroop.sayHi()
swaroop.howMany()
这是网上的代码,我抄下来运行的时候出现NoneType的错误, 后来发现问题出在倒数第三,四,五行的对象‘jack’上,我改成‘jacb’也会有同样的错误,改成‘mmmm’反而运行正确了。不明白这是什么错误,求指导,万分感激!运行结果:/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/alys/PycharmProjects/Python1/objvar.pyException AttributeError: "'NoneType' object has no attribute 'population'" in <bound method Person.__del__ of <__main__.Person instance at 0x1102d4cf8>> ignored(Initializing Swaroop)Hi, my name is Swaroop.I am the only person here.(Initializing Jack)Hi, my name is Jack.We have 2 persons here.Hi, my name is Swaroop.We have 2 persons here.Swaroop says bye.There are still 1 people hereJack says bye.Process finished with exit code 0
|
|