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 相关文章推荐
linux系统使用python获取cpu信息脚本分享
Jan 15 Python
Python实现数据库编程方法详解
Jun 09 Python
python中实现将多个print输出合成一个数组
Apr 19 Python
详解Django之admin组件的使用和源码剖析
May 04 Python
Flask框架信号用法实例分析
Jul 24 Python
Python骚操作之动态定义函数
Mar 26 Python
Python使用到第三方库PyMuPDF图片与pdf相互转换
May 03 Python
Python实现自动访问网页的例子
Feb 21 Python
django API 中接口的互相调用实例
Apr 01 Python
python压包的概念及实例详解
Feb 17 Python
Python如何配置环境变量详解
May 18 Python
浅谈Python数学建模之固定费用问题
Jun 23 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框架Laravel学习心得体会
2015/10/28 PHP
PHP简单实现冒泡排序的方法
2016/12/26 PHP
php正则表达式基本知识与应用详解【经典教程】
2017/04/17 PHP
一些常用的JS功能函数(2009-06-04更新)
2009/06/04 Javascript
用dtree实现树形菜单 dtree使用说明
2011/10/17 Javascript
使用js判断TextBox控件值改变然后出发事件
2014/03/07 Javascript
浅析js中substring和substr的方法
2015/11/09 Javascript
使用node+vue.js实现SPA应用
2016/01/28 Javascript
概述如何实现一个简单的浏览器端js模块加载器
2016/12/07 Javascript
使用jsonp实现跨域获取数据实例讲解
2016/12/25 Javascript
Angularjs分页查询的实现
2017/02/24 Javascript
原生JS实现隐藏显示图片 JS实现点击切换图片效果
2021/01/27 Javascript
详解vue-cli中的ESlint配置文件eslintrc.js
2017/09/25 Javascript
详解小程序设置缓存并且不覆盖原有数据
2019/04/15 Javascript
使vue实现jQuery调用的两种方法
2019/05/12 jQuery
Python基础之函数用法实例详解
2014/09/10 Python
Python 中的 else详解
2016/04/23 Python
python正则表达式re之compile函数解析
2017/10/25 Python
浅谈Python实现2种文件复制的方法
2018/01/19 Python
详解Django的model查询操作与查询性能优化
2018/10/16 Python
Python3之不使用第三方变量,实现交换两个变量的值
2019/06/26 Python
python 使用matplotlib 实现从文件中读取x,y坐标的可视化方法
2019/07/04 Python
python3.6编写的单元测试示例
2019/08/17 Python
Python实现不规则图形填充的思路
2020/02/02 Python
Python @property原理解析和用法实例
2020/02/11 Python
使用Python爬取弹出窗口信息的实例
2020/03/14 Python
Python3.9最新版下载与安装图文教程详解(Windows系统为例)
2020/11/28 Python
世界著名的顶级牛排:Omaha Steak(奥马哈牛排)
2016/09/20 全球购物
台湾团购、宅配和优惠券:17Life
2017/08/14 全球购物
美国玩具公司:U.S.Toy
2018/05/19 全球购物
Coccinelle官网:意大利的著名皮具品牌
2019/05/15 全球购物
大学毕业生自我鉴定
2013/11/05 职场文书
信息系统专业个人求职信范文
2013/12/07 职场文书
勤奋学习演讲稿
2014/05/10 职场文书
模具专业自荐信
2014/05/29 职场文书
大学生标准自荐书
2014/06/15 职场文书