鱼C论坛

 找回密码
 立即注册
查看: 2086|回复: 2

[已解决]如何删除类实例化出的对象,比如下面代码中的swaroop 和 kalam

[复制链接]
发表于 2018-5-6 20:48:09 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
>>> 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
        print('__del__ 被调用了!!!!!!!!!!')

        if Person.population == 0:
            print('I am the last one.')
        else:
            print('There are still %d people 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 persons here.' % Person.population)

            
>>> swaroop = Person('Swaroop_111111111111')
(Initializing Swaroop_111111111111)
>>> swaroop.sayHi()
Hi,my name is Swaroop_111111111111
>>> swaroop.howMany()
I am the only person here.
>>> kalam = Person('Kalam_222222222222')
(Initializing Kalam_222222222222)
>>> kalam.sayHi()
Hi,my name is Kalam_222222222222
>>> kalam.howMany()
We have 2 persons here.
>>>
>>> swaroop.sayHi()
Hi,my name is Swaroop_111111111111
>>> swaroop.howMany()
We have 2 persons here.
>>> Person.population
2
>>>
最佳答案
2018-5-6 21:14:28
del swaroop
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2018-5-6 21:14:28 | 显示全部楼层    本楼为最佳答案   
del swaroop
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2018-5-6 21:29:18 | 显示全部楼层

>>> del swaroop
Swaroop_111111111111 say bye.
__del__ 被调用了!!!!!!!!!!
There are still 1 people left.
>>> kalam.howMany()
I am the only person here.
>>> del kalam
Kalam_222222222222 say bye.
__del__ 被调用了!!!!!!!!!!
I am the last one.
>>> test = Person('test')
(Initializing test)
>>> test.howMany()
I am the only person here.
>>>

谢谢,试过了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-10-12 03:06

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表