Python论坛  - 讨论区

标题:[python-chinese] 类与对象的方法(教程中的代码偶执行出错,请那位有空的大大看看)

2005年12月21日 星期三 15:52

l zh lzhlds at gmail.com
Wed Dec 21 15:52:20 HKT 2005

# 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
        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

lzh = Person('lzh')
lzh.sayHi()
lzh.howMany()

lds = Person('lds')
lds.sayHi()
lds.howMany()
lzh.sayHi()
lzh.howMany()

_________________________________输出_______________________________________________________

(Initializing lzh)
Hi, my name is lzh.
I am the only person here.
(Initializing lds)
Hi, my name is lds.
We have 2 persons here.
Hi, my name is lzh.
We have 2 persons here.
lds says bye.
Exception exceptions.AttributeError: "'NoneType' object has no attribute
'population'" in <__main__.Person instance
at 0x00B14210>> ignored
lzh says bye.
Exception exceptions.AttributeError: "'NoneType' object has no attribute
'population'" in <__main__.Person instance
at 0x00B141E8>> ignored
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.exoweb.net/pipermail/python-chinese/attachments/20051221/0d308317/attachment.html

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

如下红色区域有误,请重新填写。

    你的回复:

    请 登录 后回复。还没有在Zeuux哲思注册吗?现在 注册 !

    Zeuux © 2025

    京ICP备05028076号