inspect.getmembers in order?

后端 未结 6 1937
栀梦
栀梦 2021-01-01 10:54
inspect.getmembers(object[, predicate])

Return all the members of an object in a list of (name, value) pairs sorted by nam

6条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-01 11:46

    The attributes (methods and other members) of an object is usually looked up through an object's special __dict__ attribute which is a standard Python dictionary. It doesn't guarantee any specific ordering.

    If an attribute is not found in the object's __dict__ the class's is searched instead (where methods usually reside) and so on until the whole inheritance chain has been traversed.

    Here is some custom inspection done in the interactive prompt to illustrate this (Python 3.1):

    >>> class Klass():
    ...     def test(self):
    ...             pass
    ...
    >>> k = Klass()
    >>> k.__dict__
    {}
    >>> k.__class__.__dict__.items()
    [('test', ), ('__dict__', ), ('__module__', '__main__'), ('__weakref__', ), ('__doc__', None)]
    

    Would I have put a constructor (__init__) in Klass and set an attribute through self it would've shown up in k.__dict__.

    You can circumvent this by using a custom metaclass. The documentation contains an example which does exactly what you want.

    See the bottom of this page for the OrderedClass example.

    Don't know what version of Python you have so I assumed latest.

提交回复
热议问题