inspect.getmembers in order?

后端 未结 6 1935
栀梦
栀梦 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:48

    You can use the builtin function vars() as an alternative for inspect.getmembers that returns members in the order they were defined:

    >>> class RegisterForm:
    ...     username = ""
    ...     password1 = ""
    ...     password2 = ""
    ...     first_name = ""
    ...     last_name = ""
    ...     address = ""
    ...
    >>> list(vars(RegisterForm).keys())
    ['__module__', 'username', 'password1', 'password2', 'first_name', 'last_name', 'address', '__doc__']
    

    This works starting with CPython 3.6 and all other Python implementations starting with Python 3.7, because dicts are now ordered by insertion, which means the underlying __dict__ property of a class (which is what vars() returns) is ordered.

提交回复
热议问题