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常用正则表达式符号浅析
Aug 13 Python
Python的Bottle框架中获取制定cookie的教程
Apr 24 Python
Python编程实现删除VC临时文件及Debug目录的方法
Mar 22 Python
django模板语法学习之include示例详解
Dec 17 Python
使用urllib库的urlretrieve()方法下载网络文件到本地的方法
Dec 19 Python
python实现一个简单的ping工具方法
Jan 31 Python
python图形工具turtle绘制国际象棋棋盘
May 23 Python
python代码实现逻辑回归logistic原理
Aug 07 Python
Scrapy框架实现的登录网站操作示例
Feb 06 Python
解决python3中os.popen()出错的问题
Nov 19 Python
解决pycharm导入numpy包的和使用时报错:RuntimeError: The current Numpy installation (‘D:\\python3.6\\lib\\site-packa的问题
Dec 08 Python
python实现图片转字符画
Feb 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实现memcache缓存示例讲解
2013/12/04 PHP
js和php邮箱地址验证的实现方法
2014/01/09 PHP
php mailer类调用远程SMTP服务器发送邮件实现方法
2016/03/04 PHP
Laravel 5使用Laravel Excel实现Excel/CSV文件导入导出的功能详解
2017/10/11 PHP
javascript 解析后的xml对象的读取方法细解
2009/07/25 Javascript
javascript 面向对象编程  function是方法(函数)
2009/09/17 Javascript
jquery控制listbox中项的移动并排序的实现代码
2010/09/28 Javascript
jquery插件制作简单示例说明
2012/02/03 Javascript
JS判断数组中是否有重复值得三种实用方法
2013/08/16 Javascript
谈谈我对JavaScript原型和闭包系列理解(随手笔记8)
2015/12/24 Javascript
最全面的百度地图JavaScript离线版开发
2016/09/10 Javascript
js实现3d悬浮效果
2017/02/16 Javascript
JavaScript数组去重的多种方法(四种)
2017/09/19 Javascript
解决vue组件中使用v-for出现告警问题及v for指令介绍
2017/11/11 Javascript
浅谈webpack编译vue项目生成的代码探索
2017/12/11 Javascript
Vue中Axios从远程/后台读取数据
2019/01/21 Javascript
Vue中使用wangeditor富文本编辑的问题
2021/02/07 Vue.js
Python删除windows垃圾文件的方法
2015/07/14 Python
详解Python命令行解析工具Argparse
2016/04/20 Python
Python正规则表达式学习指南
2016/08/02 Python
Python使用回溯法子集树模板获取最长公共子序列(LCS)的方法
2017/09/08 Python
解决出现Incorrect integer value: '' for column 'id' at row 1的问题
2017/10/29 Python
Python SVM(支持向量机)实现方法完整示例
2018/06/19 Python
pyqt5与matplotlib的完美结合实例
2019/06/21 Python
Python Scrapy框架第一个入门程序示例
2020/02/05 Python
Python创建空列表的字典2种方法详解
2020/02/13 Python
python 服务器运行代码报错ModuleNotFoundError的解决办法
2020/09/16 Python
Python字典取键、值对的方法步骤
2020/09/30 Python
ASICS印度官方网站:日本专业运动品牌
2020/06/20 全球购物
高级编程求职信模板
2014/02/16 职场文书
继承权公证书
2014/04/09 职场文书
消防安全宣传标语
2014/06/07 职场文书
党员群众路线自我剖析材料
2014/10/06 职场文书
天河观后感
2015/06/11 职场文书
超市员工管理制度
2015/08/06 职场文书
Vue3如何理解ref toRef和toRefs的区别
2022/02/18 Vue.js