python函数之dir()函数


本文摘自php中文网,作者巴扎黑,侵删。

dir()函数

中文说明:

你可以使用内建的dir函数来列出模块定义的标识符。标识符有函数、类和变量。

当你为dir()提供一个模块名的时候,它返回模块定义的名称列表。如果不提供参数,它返回当前模块中定义的名称列表。

首先,我们来看一下在输入的sys模块上使用dir。我们看到它包含一个庞大的属性列表。

接下来,我们不给dir函数传递参数而使用它——默认地,它返回当前模块的属性列表。注意,输入的模块同样是列表的一部分。

为了观察dir的作用,我们定义一个新的变量a并且给它赋一个值,然后检验dir,我们观察到在列表中增加了以上相同的值。我们使用del语句删除当前模块中的变量/属性,这个变化再一次反映在dir的输出中。

关于del的一点注释——这个语句在运行后被用来 删除 一个变量/名称。在这个例子中,del a,你将无法再使用变量a——它就好像从来没有存在过一样。

版本:

各版本中都支持该函数,python3中仍可用。

代码示例:

1

2

3

4

5

6

7

8

9

10

11

12

13

>>> import struct

>>> dir()   # show the names in the module namespace

['__builtins__', '__doc__', '__name__', 'struct']

>>> dir(struct)   # show the names in the struct module

['Struct', '__builtins__', '__doc__', '__file__', '__name__',

 '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',

 'unpack', 'unpack_from']

>>> class Shape(object):

        def __dir__(self):

            return ['area', 'perimeter', 'location']

>>> s = Shape()

>>> dir(s)

['area', 'perimeter', 'location']

英文说明:

dir([object])

Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.

If the object has a method named __dir__(), this method will be called and must return the list of attributes. This allows objects that implement a custom __getattr__() or __getattribute__() function to customize the way dir() reports their attributes.

If the object does not provide __dir__(), the function tries its best to gather information from the object’s __dict__ attribute, if defined, and from its type object. The resulting list is not necessarily complete, and may be inaccurate when the object has a custom __getattr__().

The default dir() mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:

If the object is a module object, the list contains the names of the module’s attributes.

If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.

Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.

以上就是python函数之dir()函数的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

paramiko模块安装使用说明

Python支持返回函数的实例解析

详解在Python中执行系统命令的方法

Python中socket模块详解

Python如何播放视频

为何选择Python进行数据分析

Python学习】面向对象的编程

Python环境变量如何配置

Python是强类型语言吗

Python生成器定义与简单用法实例分析

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...