Python基础知识内置函数dir的使用方法
Posted 知识搬运工程师
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python基础知识内置函数dir的使用方法相关的知识,希望对你有一定的参考价值。
原英文帮助文档:
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.
The resulting list is sorted alphabetically. For example:
>>> import struct >>> dir() # show the names in the module namespace # doctest: +SKIP [\'__builtins__\', \'__name__\', \'struct\'] >>> dir(struct) # show the names in the struct module # doctest: +SKIP [\'Struct\', \'__all__\', \'__builtins__\', \'__cached__\', \'__doc__\', \'__file__\', \'__initializing__\', \'__loader__\', \'__name__\', \'__package__\', \'_clearcache\', \'calcsize\', \'error\', \'pack\', \'pack_into\', \'unpack\', \'unpack_from\'] >>> class Shape: ... def __dir__(self): ... return [\'area\', \'perimeter\', \'location\'] >>> s = Shape() >>> dir(s) [\'area\', \'location\', \'perimeter\']
Note
Because dir()
is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.
————————(我是分割线)————————
中文解释:
不带参数,返回当前本地作用域的名称列表。
>>> dir() [\'__annotations__\', \'__builtins__\', \'__doc__\', \'__loader__\', \'__name__\', \'__package__\', \'__spec__\'] >>>
使用参数,尝试返回该对象的有效属性列表。
>>> a = "string" >>> dir(a) [\'__add__\', \'__class__\', \'__contains__\', \'__delattr__\', \'__dir__\', \'__doc__\', \'__eq__\', \'__format__\', \'__ge__\', \'__getattribute__\', \'__getitem__\', \'__getnewargs__\', \'__gt__\', \'__hash__\', \'__init__\', \'__init_subclass__\', \'__iter__\', \'__le__\', \'__len__\', \'__lt__\', \'__mod__\', \'__mul__\', \'__ne__\', \'__new__\', \'__reduce__\', \'__reduce_ex__\', \'__repr__\', \'__rmod__\', \'__rmul__\', \'__setattr__\', \'__sizeof__\', \'__str__\', \'__subclasshook__\', \'capitalize\', \'casefold\', \'center\', \'count\', \'encode\', \'endswith\', \'expandtabs\', \'find\', \'format\', \'format_map\', \'index\', \'isalnum\', \'isalpha\', \'isascii\', \'isdecimal\', \'isdigit\', \'isidentifier\', \'islower\', \'isnumeric\', \'isprintable\', \'isspace\', \'istitle\', \'isupper\', \'join\', \'ljust\', \'lower\', \'lstrip\', \'maketrans\', \'partition\', \'replace\', \'rfind\', \'rindex\', \'rjust\', \'rpartition\', \'rsplit\', \'rstrip\', \'split\', \'splitlines\', \'startswith\', \'strip\', \'swapcase\', \'title\', \'translate\', \'upper\', \'zfill\'] >>> >>> dir(str) [\'__add__\', \'__class__\', \'__contains__\', \'__delattr__\', \'__dir__\', \'__doc__\', \'__eq__\', \'__format__\', \'__ge__\', \'__getattribute__\', \'__getitem__\', \'__getnewargs__\', \'__gt__\', \'__hash__\', \'__init__\', \'__init_subclass__\', \'__iter__\', \'__le__\', \'__len__\', \'__lt__\', \'__mod__\', \'__mul__\', \'__ne__\', \'__new__\', \'__reduce__\', \'__reduce_ex__\', \'__repr__\', \'__rmod__\', \'__rmul__\', \'__setattr__\', \'__sizeof__\', \'__str__\', \'__subclasshook__\', \'capitalize\', \'casefold\', \'center\', \'count\', \'encode\', \'endswith\', \'expandtabs\', \'find\', \'format\', \'format_map\', \'index\', \'isalnum\', \'isalpha\', \'isascii\', \'isdecimal\', \'isdigit\', \'isidentifier\', \'islower\', \'isnumeric\', \'isprintable\', \'isspace\', \'istitle\', \'isupper\', \'join\', \'ljust\', \'lower\', \'lstrip\', \'maketrans\', \'partition\', \'replace\', \'rfind\', \'rindex\', \'rjust\', \'rpartition\', \'rsplit\', \'rstrip\', \'split\', \'splitlines\', \'startswith\', \'strip\', \'swapcase\', \'title\', \'translate\', \'upper\', \'zfill\'] >>> >>>
如果对象有一个名字叫__dir__() 的方法(函数),则将调用此方法,并且必须返回属性列表。
(大多数常见对象都有__dir__()方法 )
这允许实现自定义__getattr__()
或 __getattribute__()
函数的对象自定义dir()
报告其属性的方式。
如果对象不提供__dir__() ,则函数将尽力从对象的__dict__ 属性(如果其已经从类型对象手机信息去定义的话)
结果列表不一定完整,并且在对象具有自定义的__getattr__()时可能不准确。
默认的dir()机制,对不同类型的对象的行为不同,因为它试图生成最相关而不是最完整的信息。
如果对象是模块,则列表包含模块属性的名称。
如果对象是类型或类对象,则列表包含其属性的名称,并递归地包含其基的属性的名称。否则列表将包含对象的属性名、类的属性名,以及类的基类的递归属性名。
结果列表按字母顺序排序,如:
>>> import struct >>> dir() # show the names in the module namespace # doctest: +SKIP [\'__builtins__\', \'__name__\', \'struct\'] >>> dir(struct) # show the names in the struct module # doctest: +SKIP [\'Struct\', \'__all__\', \'__builtins__\', \'__cached__\', \'__doc__\', \'__file__\', \'__initializing__\', \'__loader__\', \'__name__\', \'__package__\', \'_clearcache\', \'calcsize\', \'error\', \'pack\', \'pack_into\', \'unpack\', \'unpack_from\'] >>> class Shape: ... def __dir__(self): ... return [\'area\', \'perimeter\', \'location\'] >>> s = Shape() >>> dir(s) [\'area\', \'location\', \'perimeter\']
备注:
因为提供dir()主要是为了方便在交互提示下使用,因此它试图提供一组有趣的名称,而不是提供一组严格或一致定义的名称,并且其详细行为可能会在不同版本中发生变化。
例如当参数是类时,元类属性不在结果列表属性中。
———————(我是分割线)————————
————————(我是分割线)————————
参考:
1. Python 3.7.2 documentation
2. RUNOOB.COM:https://www.runoob.com/python/python-func-dir.html
备注:
初次编辑时间:2019年9月21日22:06:44
第一次修改时间:2019年9月21日22:10:14 / 添加环境信息
环境:Windows 7 / Python 3.7.2
以上是关于Python基础知识内置函数dir的使用方法的主要内容,如果未能解决你的问题,请参考以下文章