1 描述
dir()函数可以查看(打印)对象的属性和方法。不管时那种对象(python中一切皆对象)类型(数据,模块)都有自己的属性和方法。
dir() 函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;
带参数时,返回参数的属性、方法列表。
如果参数包含方法__dir__(),该方法将被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息。
2 语法
dir(object)
- object -- 对象、变量、类型。
3 返回值
返回对象的属性列表
4 示例
4.1 获取当前模块的属性列表
>>> dir() [‘__builtins__‘, ‘__doc__‘, ‘__loader__‘, ‘__name__‘, ‘__package__‘, ‘__spec__‘, ‘a‘]
4.2 获取列表的的方法
>>> dir([]) [‘__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‘]
>>> a = [1,2] >>> dir(a) [‘__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‘]
两种操作方法所得结果一样,都是查看列表都有哪些操作方法及属性的
4.3 查看模块的属性、方法
>>> import time #导入模块 >>> dir(time) #查看模块 [‘CLOCK_MONOTONIC‘, ‘CLOCK_MONOTONIC_RAW‘, ‘CLOCK_PROCESS_CPUTIME_ID‘, ‘CLOCK_REALTIME‘, ‘CLOCK_THREAD_CPUTIME_ID‘, ‘_STRUCT_TM_ITEMS‘, ‘__doc__‘, ‘__loader__‘, ‘__name__‘, ‘__package__‘, ‘__spec__‘, ‘altzone‘, ‘asctime‘, ‘clock‘, ‘clock_getres‘, ‘clock_gettime‘, ‘clock_settime‘, ‘ctime‘, ‘daylight‘, ‘get_clock_info‘, ‘gmtime‘, ‘localtime‘, ‘mktime‘, ‘monotonic‘, ‘perf_counter‘, ‘process_time‘, ‘sleep‘, ‘strftime‘, ‘strptime‘, ‘struct_time‘, ‘time‘, ‘timezone‘, ‘tzname‘, ‘tzset‘]
时间: 2024-12-21 00:18:41