python – 获取所有可能的类属性的完整列表

有一种方法,给定一个简单的类,输出所有可能的属性吗?标准属性,如__class__和__doc__和 special read only attributes,如__mro__,__bases__等.一般来说,所有现有属性?

考虑一个类最简单的情况:

class myClass:
    pass

dir(),vars()和inspect.getmembers()都排除了某些内置属性.最完整的列表是使用myClass .__ dir __(MyClass)提供的,在添加内置属性时,它排除了MyClass的用户定义属性,例如:

In [3]: set(MyClass.__dir__(MyClass)) - set(dir(MyClass))
Out[3]: 
{'__abstractmethods__', '__base__', '__bases__',
 '__basicsize__', '__call__', '__dictoffset__',
 '__flags__', '__instancecheck__', '__itemsize__',
 '__mro__', '__name__', '__prepare__', '__qualname__',
 '__subclasscheck__', '__subclasses__', '__text_signature__',
 '__weakrefoffset__', 'mro'}

根据其中一个类似的问题,这是不可能的.如果目前还不可能,那么“隐藏”某些属性如__bases__(从标准调用到dir(),vars()& inspect而不是像__name__这样的属性背后的理由是什么?

类似问题:

> How to get a complete list of object’s methods and attributes?

This is the most likely to be labeled as a duplicate, but, it is old and mostly regarding Python 2.x. The accepted answer is that there isn’t a way but it was provided in 08′. The most recent answer in 12′ suggests dir() for new style classes.

> Print all properties of a Python Class

Similar title, different content.

> Getting attributes of a class

Offers dir() and inspect solutions.

> Get all object attributes in Python?

Again, proposing dir().

dir()基本上是一个方便的方法,它不应该返回所有内容,它基本上做的是它递归返回在类的字典及其基础中找到的所有内容.

PyPy’s implementation of dir()很容易理解:

def dir(*args):
    ...
    elif isinstance(obj, (types.TypeType, types.ClassType)):
        # Don't look at __class__, as metaclass methods would be confusing.
        return sorted(_classdir(obj))
    ...

def _classdir(klass):
    """Return a set of the accessible attributes of class/type klass.

    This includes all attributes of klass and all of the base classes
    recursively.
    """
    names = set()
    ns = getattr(klass, '__dict__', None)
    if ns is not None:
        names.update(ns)
    bases = getattr(klass, '__bases__', None)
    if bases is not None:
        # Note that since we are only interested in the keys, the order
        # we merge classes is unimportant
        for base in bases:
            names.update(_classdir(base))
    return names

由于每个类基本上都是从对象继承的,因此它们会包含一些dunder方法,因为它们实际上是对象字典的一部分:

>>> class A(object):
    pass
...
>>> set(dir(A)) == set(list(object.__dict__) + list(A.__dict__))
True

Now what about __bases__ and other missing items?

首先,对象本身就是某个实例,well it’s bit of a mess actually

>>> isinstance(type, object)
True
>>> isinstance(object, type)
True
>>> issubclass(type, object)
True
>>> issubclass(object, type)
False
>>> type.mro(object)
[<type 'object'>]
>>> type.mro(type)
[<type 'type'>, <type 'object'>]

所以,__bases __,__ ge__等所有属性实际上都是类型的一部分:

>>> list(type.__dict__)
['__module__', '__abstractmethods__', '__getattribute__', '__weakrefoffset__', '__dict__', '__lt__', '__init__', '__setattr__', '__subclasses__', '__new__', '__base__', '__mro__', 'mro', '__dictoffset__', '__call__', '__itemsize__', '__ne__', '__instancecheck__', '__subclasscheck__', '__gt__', '__name__', '__eq__', '__basicsize__', '__bases__', '__flags__', '__doc__', '__delattr__', '__le__', '__repr__', '__hash__', '__ge__']

因此,当我们做A .__ bases__时,我们实际上正在查找descriptor on type of A,即类型:

>>> A.__bases__
(<type 'object'>,)
>>> type(A).__dict__['__bases__'].__get__(A, type)
(<type 'object'>,)

因此,由于A是类型的实例,因此这些方法不是其自己的字典的一部分,而是其类型的字典.

>> class A(object):
...     spam = 'eggs'
...
>>> a = A()
>>> a.foo = 100
>>> a.bar = 200
>>> a.__dict__
{'foo': 100, 'bar': 200}
>>> A.__dict__
dict_proxy({'__dict__': <attribute '__dict__' of 'A' objects>, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None, 'spam': 'eggs'})

因为,type是object的子类,对类型的dir()调用将包含来自object的一些项:

>>> set(dir(type)) - set(type.__dict__)
set(['__reduce_ex__', '__str__', '__format__', '__reduce__', '__class__', '__subclasshook__', '__sizeof__'])
相关文章
相关标签/搜索