爬虫杂记

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的形式。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容