簡體   English   中英

Python:什么可以防止對象破壞?

[英]python: what prevents from object destroy?

如果在函數中定義類實例,則在函數退出時,實例將由於范圍超出而自動銷毀。 這可以通過一個小程序簡單地驗證:

class A(object):
    def __del__(self):
        print 'deleting A ', id(self)

class B(A):
    def __init__(self):
        self.a = A()

    def __del__(self):
        print 'deleting B ', id(self)
        super(B, self).__del__()


def test():
    b = B()
    print 'this is ', b

test()

輸出為:

this is  <__main__.B object at 0x01BC6150>
deleting B  29122896
deleting A  29122896
deleting A  29122960

但是我遇到一個奇怪的問題。 當我從novaclient繼承一個類時,該實例將永遠不會被自動銷毀。

from novaclient.v1_1.client import Client as NovaClient

class ViviNovaClient(NovaClient):
    def __init__(self, auth_token, url, tenant_id):
        super(ViviNovaClient, self).__init__(None, None, tenant_id, auth_url = 'http')
        self.client.management_url = url
        self.client.auth_token = auth_token
        self.client.used_keyring = True;
        LOG.info('creating <ViviNovaClient> %d' % id(self))

    def __del__(self):
        LOG.info('deleting <ViviNovaClient> %d' % id(self))


if __name__ == '__main__':
    def test():
        client = ViviNovaClient('53ef4c407fed45de915681a2d6aef1ee',                                   
          'http://135.251.237.130:8774/v2/082d8fd857f44031858827d149065d9f',
           '082d8fd857f44031858827d149065d9f')

    test()

輸出為:

2013-05-24 23:08:03 32240 INFO vivi.vivimain.ViviNovaClient [-] creating <ViviNovaClient> 26684304

在此測試中,不會破壞“客戶端”對象。 因此,我想知道什么會阻止“客戶端”對象自動銷毀?

由於許多其他對象也存儲着對客戶端的引用,因此形成了許多引用周期

例如,從源代碼

class Client(object):
    def __init__(self, username, **etc):
        password = api_key
        self.project_id = project_id
        self.flavors = flavors.FlavorManager(self)
        # etc.

我們看到客戶端將保存FlavorManager,而FlavorManager的初始化程序(即Manager )也將保存對輸入Client的引用:

class Manager(utils.HookableMixin):
    def __init__(self, api):
        self.api = api

在Python啟動循環收集器之前,不會立即刪除這些對象。 請注意,添加__del__方法會阻止循環收集器運行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM