您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python内置函数dir详解

5b51 2022/1/14 8:17:34 python 字数 4597 阅读 347 来源 www.jb51.cc/python

1.命令介绍 最近学习并使用了一个python的内置函数dir,首先help一下: 复制代码代码如下:

概述

1.命令介绍

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


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.


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))

if __name__ == '__main__':
    print("dir module A:",dir(A))

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

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

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

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

if __name__ == '__main__':
    print("dir without arguments:",dir(a.a))
    print("dir current file:",curModuleDir)

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

if __name__ == '__main__':
    print("dir without arguments:",dir(this))

class A:
    def a(self):
        pass

class A1(A):
    def a1(self):
        pass

if __name__ == '__main__':
    print("dir without arguments:",dir(sys.modules[__name__])) # 使用__name__获取当前module对象,然后使用对象获得dir

总结

以上是编程之家为你收集整理的Python内置函数dir详解全部内容,希望文章能够帮你解决Python内置函数dir详解所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶