当前位置: 首页 > 图灵资讯 > 行业资讯> python入门必会的助手函数:dir()函数

python入门必会的助手函数:dir()函数

发布时间:2025-09-29 11:05:20

让我们来看看今天一个非常重要的函数:dir()

中文描述:当没有参数时,返回当前范围内的变量、方法和定义类型列表;当带有参数时,返回参数的属性和方法列表。如果参数包含方法__dir__()这种方法将被调用。如果参数不包括__dir__(),该方法将限制参数信息的收集。

object参数: 对象、变量、类型。

版本:这个函数在python的每个版本中都有,但是每个版本中显示的属性细节是不同的。使用时注意差异。

英文说明:

dir([object])

Withoutarguments,returnthelistofnamesinthecurrentlocalscope.Withanargument,attempttoreturnalistof
validattributesforthatobject.

Iftheobjecthasamethodnamed__dir__(),thismethodwillbecalledandmustreturnthelistofattributes.This
allowsobjectsthatimplementacustom__getattr__()or__getattribute__()functiontocustomizethewaydir()
reportstheirattributes.

Iftheobjectdoesnotprovide__dir__(),thefunctiontriesitsbesttogatherinformationfromtheobject’
s__dict__attribute,ifdefined,andfromitstypeobject.Theresultinglistisnotnecessarilycomplete,andmaybe
inaccuratewhentheobjecthasacustom__getattr__().

Thedefaultdir()mechanismbehavesdifferentlywithdifferenttypesofobjects,asitattemptstoproducethemost
relevant,ratherthancomplete,information:

Iftheobjectisamoduleobject,thelistcontainsthenamesofthemodule’sattributes.

Iftheobjectisatypeorclassobject,thelistcontainsthenamesofitsattributes,andrecursivelyofthe
attributesofitsbases.

Otherwise,thelistcontainstheobject’sattributes’names,thenamesofitsclass’sattributes,andrecursively
oftheattributesofitsclass’sbaseclasses.

例如

>>>importstruct
>>>dir()#showthenamesinthemodulenamespace
['__builtins__','__doc__','__name__','struct']
>>>dir(struct)#showthenamesinthestructmodule
['Struct','__builtins__','__doc__','__file__','__name__',
'__package__','_clearcache','calcsize','error','pack','pack_into',
'unpack','unpack_from']
>>>classShape(object):
def__dir__(self):
return['area','perimeter','location']
>>>s=Shape()
>>>dir(s)
['area','perimeter','location']
NoteBecausedir()issuppliedprimarilyasaconvenienceforuseataninteractiveprompt,ittriestosupplyan
interestingsetofnamesmorethanittriestosupplyarigorouslyorconsistentlydefinedsetofnames,andits
detailedbehaviormaychangeacrossreleases.Forexample,metaclassattributesarenotintheresultlistwhenthe
argumentisaclass.

代码实例

>>>dir()
['__builtins__','__doc__','__name__','__package__']
>>>importstruct
>>>dir()
['__builtins__','__doc__','__name__','__package__','struct']
>>>dir(struct)
['Struct','__builtins__','__doc__','__file__','__name__','__package__','_clearcache','calcsize','error','pack',
'pack_into','unpack','unpack_from']
>>>classPerson(object):
...def__dir__(self):
...return["name","age","country"]
...
>>>dir(Person)
['__class__','__delattr__','__dict__','__dir__','__doc__','__format__','__getattribute__','__hash__','__init__',
'__module__','__new__','__reduce__','__reduce_ex__','__repr__','__setattr__','__sizeof__','__str__','__subclasshook__',
'__weakref__']
>>>tom=Person()
>>>dir(tom)
['age','country','name']

相关文章

Python中lambda表达式的优缺点及使用场景

Python中lambda表达式的优缺点及使用场景

2025-09-29
详解json.dumps中文乱码问题

详解json.dumps中文乱码问题

2025-09-29
Python和单元测试那些事儿

Python和单元测试那些事儿

2025-09-29
Python正则表达式findall函数详解

Python正则表达式findall函数详解

2025-09-29
python入门必会的助手函数:dir()函数

python入门必会的助手函数:dir()函数

2025-09-29
Python的高级特性:容易忽略的不可变类型

Python的高级特性:容易忽略的不可变类型

2025-09-28