If the object is a module object, the list contains the names of the module’s attributes.
If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.
Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.
The resulting list is sorted alphabetically. For example:
>>> import struct >>> dir() # show the names in the module namespace ['__builtins__', '__doc__', '__name__', 'struct'] >>> dir(struct) # show the names in the struct module ['Struct', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into', 'unpack', 'unpack_from'] >>> class Shape(object): def __dir__(self): return ['area', 'perimeter', 'location'] >>> s = Shape() >>> dir(s)
代码实例:
>>> dir() ['__builtins__', '__doc__', '__name__', '__package__'] >>> import struct >>> dir() ['__builtins__', '__doc__', '__name__', '__package__', 'struct'] >>> dir(struct) ['Struct', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_clearcache', 'calcsize','error', 'pack', 'pack_into', 'unpack', 'unpack_from'] >>> class Person(object): ... def __dir__(self): ... return ["name", "age", "country"] ... >>> dir(Person) ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__format__', '__getattribute__','__hash__', '__init__', '__module__', '__new__', '__reduce__','__reduce_ex__', '__repr__','__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__'] >>> tom = Person() >>> dir(tom) ['age', 'country', 'name']
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did86966