Python函数-dir()

dir([object])函数

作用

没有参数,返回当前本地范围内的名称列表。使用参数,试图返回该对象的有效属性的列表。

说明:

默认dir()机制表现出有不同类型的对象,因为它试图产生最相关的,而不是完整的信息:
如果对象是模块对象,则列表包含模块属性的名称。
如果对象是类型或类对象,则列表包含其属性的名称,并递归地表示其属性的属性。
否则,列表包含对象的属性名称、类的属性名称和递归的类的基类的属性。

实例:

 1 >>> import struct
 2 >>> dir()   # show the names in the module namespace
 3 ['__builtins__', '__doc__', '__name__', 'struct']
 4 >>> dir(struct)   # show the names in the struct module
 5 ['Struct', '__builtins__', '__doc__', '__file__', '__name__',
 6  '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 7  'unpack', 'unpack_from']
 8 >>> class Shape(object):
 9         def __dir__(self):
10             return ['area', 'perimeter', 'location']
11 >>> s = Shape()
12 >>> dir(s)
13 ['area', 'perimeter', 'location']
原文地址:https://www.cnblogs.com/guyuyuan/p/6831676.html