【Python】显示对象的所有 Attribute

Posted by 西维蜀黍 on 2019-12-06, Last Modified on 2021-09-21

dir

my_list = [1, 2, 3]
dir(my_list)
# Output: ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
# '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
# '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__',
# '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__',
# '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__',
# '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__',
# '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop',
# 'remove', 'reverse', 'sort']

inspect module

The inspect module also provides several useful functions to get information about live objects. For example you can check the members of an object by running:

import inspect
print(inspect.getmembers(str))
# Output: [('__add__', <slot wrapper '__add__' of ... ...

Inheritance Of Attributes

Before opening this topic, let’s take a look at the built-in __dict__ attribute.

class Example:
    classAttr = 0
    def __init__(self, instanceAttr):
        self.instanceAttr = instanceAttra = Example(1)
print(a.__dict__)
print(Example.__dict__)Output:
{'instanceAttr': 1}
{'__module__': '__main__', '__doc__': None, '__dict__': <attribute '__dict__' of 'Example' objects>, '__init__': <function Example.__init__ at 0x7f8af2113f28>, 'classAttr': 0, '__weakref__': <attribute '__weakref__' of 'Example' objects>}

Reference