Dill.detect.children对象类型

时间:2014-09-03 16:06:41

标签: python pickle dill

Dill.detect.children需要两个参数; objobjtype

检查 audiofile 对象,我可以致电:

dill.detect.children(audiofile, object)
dill.detect.children(audiofile, dict)
dill.detect.children(audiofile, list)

哪个返回没有错误。

但是如何寻找实例方法?

type(audiofile.save)

返回

instancemethod

尝试

dill.detect.children(audiofile, instancemethod)

返回

NameError: name 'instancemethod' is not defined

尝试

dill.detect.children(audiofile, 'instancemethod')

返回

TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types

这不应该与调用dir(audiofile)返回类似的结果吗?

1 个答案:

答案 0 :(得分:1)

使用types.MethodType

  

<强> types.MethodType

     

用户定义的类实例的方法类型。

>>> import types
>>> print types.MethodType
<type 'instancemethod'>
>>> p = Process()
>>> type(p.start) == types.MethodType
True

但是,我不认为dill.detect.children做你认为它做的事情。它的文档说:

children(obj, objtype, depth=1, ignore=())
    Find the chain of referrers for obj. Chain will start with obj.

    objtype: an object type or tuple of types to search for
    depth: search depth (e.g. depth=2 is 'grandparents')
    ignore: an object or tuple of objects to ignore in the search

    NOTE: a common thing to ignore is all globals, 'ignore=globals()'

    NOTE: repeated calls may yield different results, as python stores
    the last value in the special variable '_'; thus, it is often good
    to execute something to replace '_' (e.g. >>> 1+1).

这与“查找obj上匹配类型objtype”的所有属性不同,它至少显示的是您期望它做的事情。