美文网首页
爬虫杂记

爬虫杂记

作者: rebirthwyw | 来源:发表于2017-09-01 23:36 被阅读0次

    update:2017-9-1
    每到deadline开发都十分有动力,XD。

    分布式模块celery

    Django后端

    • 遇到一个和循环引用相关的问题,类似下面的情况:
    class B(object):
        def __init__(self, arg):
            self.arg = arg
    
    class A(object):
        def __init__(self):
            self.b = B(self)
    
    a = A()
    

    不确定python的回收机制会不会处理这样的情况,谷歌一番后找到了一个解决的方法。
    首先在overflow上看到这么一个回答

    "Worry" is misplaced, but if your program turns out to be slow,consume more 
    memory than expected, or have strange inexplicable pauses,the cause is 
    indeed likely to be in those garbage reference loops -- they need to be 
    garbage collected by a different procedure than "normal" (acyclic) reference 
    graphs, and that collection is occasional and may be slow if you have a lot 
    of objects tied up in such loops
    

    大概的意思是对循环引用的回收不太靠谱???
    然后看到了一个解决循环引用的方法,就是weakref这个包。
    使用起来很方便,import 这个包,然后在需要的位置加上weakref.ref
    函数就好了。
    比如对上面函数的修改

    class B(object):
        def __init__(self, arg):
            self.arg = weakref.ref(arg)
    
    class A(object):
        def __init__(self):
            self.b = B(self)
    
    a = A()
    

    两次运行打印A的对象就会发现不同。

    第一次

    without weakref

    第二次

    with weakref

    最后,使用加了weakref的对象使用属性的时候,比如要用A的a属性,要写A().a的形式。

    相关文章

      网友评论

          本文标题:爬虫杂记

          本文链接:https://www.haomeiwen.com/subject/ayvbdxtx.html