首页 / PYTHON / python函数之dir()函数
python函数之dir()函数
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python函数之dir()函数,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2576字,纯文字阅读大概需要4分钟。
内容图文
![python函数之dir()函数](/upload/InfoBanner/zyjiaocheng/430/5ee1558e00ae4e7886f7c3a00dbbea41.jpg)
dir()函数
中文说明:
你可以使用内建的dir函数来列出模块定义的标识符。标识符有函数、类和变量。
当你为dir()提供一个模块名的时候,它返回模块定义的名称列表。如果不提供参数,它返回当前模块中定义的名称列表。
首先,我们来看一下在输入的sys模块上使用dir。我们看到它包含一个庞大的属性列表。
接下来,我们不给dir函数传递参数而使用它——默认地,它返回当前模块的属性列表。注意,输入的模块同样是列表的一部分。
为了观察dir的作用,我们定义一个新的变量a并且给它赋一个值,然后检验dir,我们观察到在列表中增加了以上相同的值。我们使用del语句删除当前模块中的变量/属性,这个变化再一次反映在dir的输出中。
关于del的一点注释——这个语句在运行后被用来 删除 一个变量/名称。在这个例子中,del a,你将无法再使用变量a——它就好像从来没有存在过一样。
版本:
各版本中都支持该函数,python3中仍可用。
代码示例:
>>> 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()函数的详细内容,更多请关注Gxl网其它相关文章!
内容总结
以上是互联网集市为您收集整理的python函数之dir()函数全部内容,希望文章能够帮你解决python函数之dir()函数所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。