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安装以及IDE的配置教程
Apr 29 Python
利用python模拟实现POST请求提交图片的方法
Jul 25 Python
python中yaml配置文件模块的使用详解
Apr 27 Python
关于python多重赋值的小问题
Apr 17 Python
PyQt5重写QComboBox的鼠标点击事件方法
Jun 25 Python
使用Filter过滤python中的日志输出的实现方法
Jul 17 Python
安装2019Pycharm最新版本的教程详解
Oct 22 Python
Python使用Tkinter实现转盘抽奖器的步骤详解
Jan 06 Python
Pytorch 计算误判率,计算准确率,计算召回率的例子
Jan 18 Python
python实现将range()函数生成的数字存储在一个列表中
Apr 02 Python
python实现单机五子棋
Aug 28 Python
Python实现随机爬山算法
Jan 29 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
关于Iframe如何跨域访问Cookie和Session的解决方法
2013/04/15 PHP
PHPMailer发送HTML内容、带附件的邮件实例
2014/07/01 PHP
php中判断数组相等的方法以及数组运算符介绍
2015/03/30 PHP
PHP ADODB实现分页功能简单示例
2018/05/25 PHP
微信JSSDK分享功能图文实例详解
2019/04/08 PHP
php 使用mpdf实现指定字段配置字体样式的方法
2019/07/29 PHP
javascript 点击整页变灰的效果(可做退出效果)。
2008/01/09 Javascript
用jquery ajax获取网站Alexa排名的代码
2009/12/12 Javascript
JQuery 常用操作代码
2010/03/14 Javascript
jquery全选/全不选/反选另一种实现方法(配合原生js)
2013/04/07 Javascript
基于JQuery 选择器使用说明介绍
2013/04/18 Javascript
jQuery实现的一个tab切换效果内部还嵌有切换
2014/08/10 Javascript
jQuery实现返回顶部效果的方法
2015/05/29 Javascript
你一定会收藏的Nodejs代码片段
2016/02/04 NodeJs
Javascript表单特效之十大常用原理性样例代码大总结
2016/07/12 Javascript
JavaScript 实现的checkbox经典实例分享
2016/10/16 Javascript
Jquery EasyUI Datagrid右键菜单实现方法
2016/12/30 Javascript
JavaScript中Require调用js的实例分享
2017/10/27 Javascript
Javacript中自定义的map.js  的方法
2017/11/26 Javascript
原生js实现trigger方法示例代码
2019/05/22 Javascript
JS使用cookie保存用户登录信息操作示例
2019/05/30 Javascript
关于ligerui子页面关闭后,父页面刷新,重新加载的方法
2019/09/27 Javascript
JS FormData对象使用方法实例详解
2020/02/12 Javascript
JS实现简易贪吃蛇游戏
2020/08/24 Javascript
js前端对于大量数据的展示方式及处理方法
2020/12/02 Javascript
[01:45]典藏宝瓶2+祈求者身心——这就是DOTA2TI9总奖金突破3000万美元的秘密
2019/07/21 DOTA
Python新手在作用域方面经常容易碰到的问题
2015/04/03 Python
Python matplotlib 画图窗口显示到gui或者控制台的实例
2018/05/24 Python
python树莓派红外反射传感器
2019/01/21 Python
Python 数据可视化pyecharts的使用详解
2019/06/26 Python
英国最大的女性服装零售商:Dorothy Perkins
2017/03/30 全球购物
REN Clean Skincare官网:英国本土有机护肤品牌
2019/02/23 全球购物
智能室内花园:Click & Grow
2021/01/29 全球购物
电脑销售顾问自荐信
2014/01/29 职场文书
pdf论文中python画的图Type 3 fonts字体不兼容的解决方案
2021/04/24 Python
新手初学Java List 接口
2021/07/07 Java/Android