本函数是用来显示当前作用域里的属性列表,或者参数对象object的属性列表。当没有参数对象时,显示当前作用域所在的属性列表;如果有参数对象,就会显示这个对象拥有的属性列表。本函数在显示对象的属性列表时,查看对象是否存在__dir__()函数,如果存在,就调用这个函数,并显示这个函数返回的属性列表。当然用户也可以使用__getattr__()或__getattribute__()函数来定制属性的显示。如果对象没有定义__dir__()函数,尝试从对象的__dict__属性来获取属性列表,这样来可能显示属性就不是那么准确了,可能有些属性没有显示,特别使用__getattr__()函数来获取属性的方式。
本函数设计的机制是这样的:对不同的类型对象,显示不同属性列表,但主要的原则是显示最重要的属性,而不是全部信息显示方面作为重点。
1)如果对象是一个模块对象,属性列表显示主要是对象的名称属性列表。
2)如果对象是一个类型或类对象,主要显示是属性名称,并且递归地显示基类的属性名称。
3)如果对象是其它类型,主要显示属性名称,类属性名称,递归到基类属性名称。
例子:
#dir()函数 import struct print(dir(struct)) print(dir()) l = [1, 2, 3] print(dir(l)) print(dir(‘a‘)) class Shape: def __dir__(self): return [‘area‘, ‘perimeter‘, ‘location‘] s = Shape() print(dir(s))
结果输出如下:
[‘Struct‘, ‘__all__‘, ‘__builtins__‘, ‘__cached__‘, ‘__doc__‘, ‘__file__‘, ‘__loader__‘, ‘__name__‘, ‘__package__‘, ‘__spec__‘, ‘_clearcache‘, ‘calcsize‘, ‘error‘, ‘iter_unpack‘, ‘pack‘, ‘pack_into‘, ‘unpack‘, ‘unpack_from‘]
[‘__builtins__‘, ‘__cached__‘, ‘__doc__‘, ‘__file__‘, ‘__loader__‘, ‘__name__‘, ‘__package__‘, ‘__spec__‘, ‘struct‘]
[‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__delitem__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__gt__‘, ‘__hash__‘, ‘__iadd__‘, ‘__imul__‘, ‘__init__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__mul__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__reversed__‘, ‘__rmul__‘, ‘__setattr__‘, ‘__setitem__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘append‘, ‘clear‘, ‘copy‘, ‘count‘, ‘extend‘, ‘index‘, ‘insert‘, ‘pop‘, ‘remove‘, ‘reverse‘, ‘sort‘]
[‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__getnewargs__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__mod__‘, ‘__mul__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__rmod__‘, ‘__rmul__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘capitalize‘, ‘casefold‘, ‘center‘, ‘count‘, ‘encode‘, ‘endswith‘, ‘expandtabs‘, ‘find‘, ‘format‘, ‘format_map‘, ‘index‘, ‘isalnum‘, ‘isalpha‘, ‘isdecimal‘, ‘isdigit‘, ‘isidentifier‘, ‘islower‘, ‘isnumeric‘, ‘isprintable‘, ‘isspace‘, ‘istitle‘, ‘isupper‘, ‘join‘, ‘ljust‘, ‘lower‘, ‘lstrip‘, ‘maketrans‘, ‘partition‘, ‘replace‘, ‘rfind‘, ‘rindex‘, ‘rjust‘, ‘rpartition‘, ‘rsplit‘, ‘rstrip‘, ‘split‘, ‘splitlines‘, ‘startswith‘, ‘strip‘, ‘swapcase‘, ‘title‘, ‘translate‘, ‘upper‘, ‘zfill‘]
[‘area‘, ‘location‘, ‘perimeter‘]