代码之家  ›  专栏  ›  技术社区  ›  Bryan Oakley

python inspect.isclass为什么认为实例是类?

  •  5
  • Bryan Oakley  · 技术社区  · 14 年前

    class Dummy(dict):
        def __init__(self, data):
            for key, value in data.iteritems():
                self.__setattr__(key, value)
    
        def __getattr__(self, attr):
            return self.get(attr, None)
        __setattr__=dict.__setitem__
        __delattr__=dict.__delitem__
    
    
    foo=Dummy({"one":1, "two":2})
    

    为什么 foo 显示在的输出中 inspect.getmembers(..., predicate=inspect.isclass)

    $ python2.5
    Python 2.5.2 (r252:60911, Aug 28 2008, 13:13:37) 
    [GCC 4.1.2 20071124 (Red Hat 4.1.2-42)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import junk
    >>> import inspect
    >>> inspect.getmembers(junk, predicate=inspect.isclass)
    [('Dummy', <class 'junk.Dummy'>), ('foo', {'two': 2, 'one': 1})]
    >>> inspect.isclass(junk.foo)
    True
    

    我早料到了 inspect 只会回来 Dummy

    2 回复  |  直到 9 年前
        1
  •  10
  •   Jon-Eric    14 年前

    在Python v2.7之前, inspect.isclass __bases__ 属性必须是类。

    Dummy __getattr__ 使 笨蛋 实例似乎具有 属性(值为 None ).

    检验分类 , foo 似乎是一个类。

    注: __getattr__ should raise AttributeError when asked for an attribute it does not know about. (这与返回 .)

        2
  •  4
  •   mouad    14 年前

    首先,如果回答得很好的话,我想补充一些东西:

    %psource inspect.isclass
    

    你将得到:

    return isinstance(object, types.ClassType) or hasattr(object, '__bases__')
    

    但我猜您使用的是python<2.6,这个bug已经修复,这是python2.7中inspect.isclass()的代码:

    return isinstance(object, (type, types.ClassType))