跳转到主要内容

提供访问对象引用(子对象)的API。

项目描述

sw.objectinspection

ObjectInspection是一个工具,它提供了一个通用的API来检查对象的属性及其子对象。它包含两个基本检查器(BasicAttributesInspectorBasicChildrenInspector),这些检查器可以很容易地替换为您自己的检查器。

设置

创建一些将要检查的对象

>>> class Child1(object):
...     pass
>>> class Child2(object):
...     pass
>>> class Child3(object):
...     pass
>>> class Child4(object):
...     misc = Child1()
>>> class ToInspect(object):
...     some_var = ["some tupel", (Child2(), Child3())]
...     other_var = {"foo": "bar"}
...     _private_var = 10
...     desc = Child4()
...
...     def some_method(self):
...         pass

检查属性

通过适配 IAttributesInspector 获取 AttributesInspector

>>> from sw.objectinspection import IAttributesInspector
>>> inspector = IAttributesInspector(ToInspect())

因为没有为 ToInspect 对象注册专门的检查器,所以使用 BasicAttributesInspector

>>> inspector
<sw.objectinspection.BasicAttributesInspector object at 0x11f69d0
 used for ToInspect object at 0x11f6910>

要开始检查,只需调用检查器

>>> inspector()
['desc', 'other_var', 'some_var']

检查子对象

对子对象的检查与对属性的检查方式相同

>>> from sw.objectinspection import IChildrenInspector
>>> inspector = IChildrenInspector(ToInspect())
>>> inspector
<sw.objectinspection.BasicChildrenInspector object at 0x11f6a10
 used for ToInspect object at 0x11f6910>
>>> sorted(inspector())
[<Child2 object at 0x119cc10>,
 <Child3 object at 0x11f5790>,
 <Child4 object at 0x11f5830>]

编写自己的检查器

您可以编写自己的检查器,并将其注册为一个比该包中提供的基检查器更特殊的适配器

>>> from sw.objectinspection import BasicInspector
>>> import zope.component
>>> import zope.interface
>>> class DummyAttributesInspector(BasicInspector):
...     zope.component.adapts(ToInspect)
...     zope.interface.implements(IAttributesInspector)
...
...     def __call__(self):
...         # The object, which is to be inspected, can be accessed
...         # with self._inspecting
...         return ['foo', 'bar']
>>> gsm = zope.component.getGlobalSiteManager()
>>> gsm.registerAdapter(DummyAttributesInspector)

现在,当检查 ToInspect 的属性时,我们得到我们的 DummyAttributesInspector

>>> inspector = IAttributesInspector(ToInspect())
>>> inspector
<DummyAttributesInspector object at 0x11f69d0
 used for ToInspect object at 0x11f6910>
>>> inspector()
['foo', 'bar']

变更记录

1.0.1 (2009-08-13)

  • 修复运行Windows的系统的内存地址检查器。

1.0 (2009-07-29)

  • 初始版本。

项目详情


下载文件

下载适用于您的平台的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源分布

sw.objectinspection-1.0.1.tar.gz (6.2 kB 查看哈希值)

上传时间 源代码

支持者