Python内置函数dir详解


Posted in Python onApril 14, 2015

1.命令介绍

最近学习并使用了一个python的内置函数dir,首先help一下:

>>> help(dir)

Help on built-in function dir in module __builtin__:


dir()

    dir([object]) -> list of strings


    Return an alphabetized list of names comprising (some of) the attributes

    of the given object, and of attributes reachable from it:


    No argument:  the names in the current scope.

    Module object:  the module attributes.

    Type or class object:  its attributes, and recursively the attributes of

        its bases.

    Otherwise:  its attributes, its class's attributes, and recursively the

        attributes of its class's base classes.

通过help,可以简单的认为dir列出指定对象或类的属性。
2.实例
下面是一个简单的测试:
 class A:

     def a(self):

         pass

 

 

 class A1(A):

    def a1(self):

        pass


if __name__ == '__main__':

    print("dir without arguments:", dir())

    print("dir class A:", dir(A))

    print("dir class A1:", dir(A1))

    a = A1()

    print("dir object a(A1):", dir(a))

    print("dir function a.a:", dir(a.a))

测试结果:
dir without arguments: ['A', 'A1', '__builtins__', '__doc__', '__file__', '__name__', '__package__']

dir class A: ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a']

dir class A1: ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'a1']

dir object a(A1): ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'a1']

dir function a.a: ['__call__', '__class__', '__delattr__', '__doc__', '__eq__', '__format__', '__func__', '__ge__', '__get__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

3.使用dir查找module下的所有类
最初使用这个函数的初衷,就是在一个module中查找实现的类名,通过该函数可以很容易的实现。
比如把上面的测试程序保存为A.py,再建一个测试程序,内容如下:
import A
if __name__ == '__main__':

    print("dir module A:", dir(A))

结果如下:
dir module A: ['A', 'A1', '__builtins__', '__doc__', '__file__', '__name__', '__package__']

可以看出class A和A1都能够找到。

4.如何找到当前模块下的类

这是一个烦恼较长时间的一个问题,也没有搜到详细的解决方法,下面是我的集中实现方法。

4.1.方法一:在module下面直接调用

比如在上面的A.py最下面添加一行,即可在后续的代码中可以使用selfDir来查找当前的module下的类,修改后的代码如下:

 class A:

     def a(self):

         pass

 

 class A1(A):

     def a1(self):

         pass

 

 curModuleDir=dir()  # get dir of current file(module)
if __name__ == '__main__':

    print("dir without arguments:", dir())

    print("dir class A:", dir(A))

    print("dir class A1:", dir(A1))

    a = A1()

    print("dir object a(A1):", dir(a))

    print("dir function a.a:", dir(a.a))

    print("dir current file:", curModuleDir)

4.2.方法二:import当前module
把当前module和别的import一样引用,代码如下:

 # A.py

 import A as this # import current module

 

 class A:

     def a(self):

         pass

 

 class A1(A):

     def a1(self):

        pass
if __name__ == '__main__':

    print("dir without arguments:", dir())

    print("dir class A:", dir(A))

    print("dir class A1:", dir(A1))

    a = A1()

    print("dir object a(A1):", dir(a))

    print("dir function a.a:", dir(a.a))

    print("dir current file:", dir(this))

4.3.方法三:根据module名称查找module,然后调用dir
我们知道module下面有个属性__name__显示module名称,怎么能够根据module名称来查找module对象呢?可以借助sys.modules。代码如下:
import sys
class A:

    def a(self):

        pass
class A1(A):

    def a1(self):

        pass
if __name__ == '__main__':

    print("dir without arguments:", dir())

    print("dir class A:", dir(A))

    print("dir class A1:", dir(A1))

    a = A1()

    print("dir object a(A1):", dir(a))

    print("dir function a.a:", dir(a.a))

    print("dir current file:", dir(sys.modules[__name__])) # 使用__name__获取当前module对象,然后使用对象获得dir
Python 相关文章推荐
Python生成随机MAC地址
Mar 10 Python
用Python实现服务器中只重载被修改的进程的方法
Apr 30 Python
django接入新浪微博OAuth的方法
Jun 29 Python
python cx_Oracle的基础使用方法(连接和增删改查)
Nov 19 Python
python逆向入门教程
Jan 15 Python
详谈python3中用for循环删除列表中元素的坑
Apr 19 Python
python for循环remove同一个list过程解析
Aug 14 Python
django使用xadmin的全局配置详解
Nov 15 Python
Python 时间戳之获取整点凌晨时间戳的操作方法
Jan 28 Python
python文件排序的方法总结
Sep 13 Python
Lombok插件安装(IDEA)及配置jar包使用详解
Nov 04 Python
Elasticsearch 聚合查询和排序
Apr 19 Python
Python最基本的数据类型以及对元组的介绍
Apr 14 #Python
Python isinstance函数介绍
Apr 14 #Python
Python with用法实例
Apr 14 #Python
详细探究Python中的字典容器
Apr 14 #Python
Python中decorator使用实例
Apr 14 #Python
用Python创建声明性迷你语言的教程
Apr 13 #Python
Python中的Numeric包和Numarray包使用教程
Apr 13 #Python
You might like
php实现从ftp服务器上下载文件树到本地电脑的程序
2009/02/10 PHP
php的日期处理函数及uchome的function_coomon中日期处理函数的研究
2011/01/12 PHP
利用Ffmpeg获得flv视频缩略图和视频时间的代码
2011/09/15 PHP
php UBB 解析实现代码
2011/11/27 PHP
PHP版 汉字转码的实现详解
2013/06/09 PHP
Yii核心组件AssetManager原理分析
2014/12/02 PHP
PHP实现的浏览器检查类
2016/04/11 PHP
浅谈PHP中pack、unpack的详细用法
2018/03/12 PHP
js电信网通双线自动选择技巧
2008/11/18 Javascript
js下通过getList函数实现分页效果的代码
2010/09/17 Javascript
分享20款好玩的jQuery游戏
2011/04/17 Javascript
jQuery对表单元素的取值和赋值操作代码
2011/05/19 Javascript
JS复制内容到剪切板的实例代码(兼容IE与火狐)
2013/11/19 Javascript
js的参数有长度限制吗?发现不能超过2083个字符
2014/04/20 Javascript
基于BootStrap Metronic开发框架经验小结【七】数据的导入、导出及附件的查看处理
2016/05/12 Javascript
基于angularJS的表单验证指令介绍
2016/10/21 Javascript
基于Nodejs利用socket.io实现多人聊天室
2017/02/22 NodeJs
几种响应式文字详解
2017/05/19 Javascript
jQuery插件DataTables分页开发心得体会
2017/08/22 jQuery
Three.js加载外部模型的教程详解
2017/11/10 Javascript
基于Vue的移动端图片裁剪组件功能
2017/11/28 Javascript
LayUi中接口传数据成功,表格不显示数据的解决方法
2018/08/19 Javascript
轻松解决JavaScript定时器越走越快的问题
2019/05/13 Javascript
python实现的各种排序算法代码
2013/03/04 Python
Python中的面向对象编程详解(下)
2015/04/13 Python
在Python的struct模块中进行数据格式转换的方法
2015/06/17 Python
Python while 循环使用的简单实例
2016/06/08 Python
Python使用matplotlib填充图形指定区域代码示例
2018/01/16 Python
python flask中动态URL规则详解
2019/11/22 Python
python datetime时间格式的相互转换问题
2020/06/11 Python
CSS3动画animation实现云彩向左滚动
2014/05/09 HTML / CSS
不用游标的SQL语句有哪些
2012/09/07 面试题
招商业务员岗位职责
2013/12/16 职场文书
初中地理教学反思
2014/01/11 职场文书
大学生党员自我评价范文
2014/04/09 职场文书
《女娲补天》教学反思
2016/02/20 职场文书