Tutorial Study Image

Python dir()

dir 函数将一个对象作为输入,并返回该对象的所有属性。这些属性以列表的形式返回。


dir(object) # object is any python object 
 

dir() 参数

dir() 函数接受一个对象作为参数。内置对象和用户定义对象都可以作为参数传入。即使不传入参数,也不会引发错误。

参数 描述 必需/可选
对象 任何需要返回其属性的 Python 对象 可选

dir() 返回值

该函数返回传入对象的所有属性,包括内置属性。如果未传入参数,则返回当前局部作用域中的名称。

输入 返回值
None 返回当前局部作用域中的名称列表。
对象 返回传入对象的属性

Python 中 dir() 方法的示例

示例 1:传入内置对象


letters = {'a':1, 'b':2, 'c':3}
# Dictionary is a built in object in python 
print(dir(letters))
 

输出

[' class   ', '   contains   ', '   delattr   ', '   delitem   ', '   dir   ', '   doc   ', '   eq   ',
' format   ', '   ge   ', '   getattribute   ', '   getitem   ', '   gt   ', '   hash   ', '   init   ',
'    init_subclass    ', '    iter    ', '    le    ', '    len    ', '    lt    ', '    ne    ', '    new    ', '    reduce    ', ' reduce_ex ', ' repr ', ' setattr ', ' setitem ', ' sizeof ', ' str ',
' subclasshook ', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

示例 2:不传入参数


print(dir())
 

输出

['    annotations    ', '    builtins    ', '    cached    ', '    doc    ', '    file    ', '    loader    ', '  name ', ' package ', ' spec ']

示例 3:传入用户定义对象


class Student:
name = "Ram" 
age = 22
course = "Bachelors" 
Student1 = Student() 
print(dir(Student1))
 

输出

['    class    ', '    delattr    ', '    dict    ', '    dir    ', '    doc    ', '    eq    ', '    format    ', '    ge    ', ' getattribute ', ' gt ', ' hash ', ' init ', ' init_subclass ', ' le ', ' lt ',
'    module    ', '    ne    ', '    new    ', '    reduce    ', '    reduce_ex    ', '    repr    ', '    setattr    ', ' sizeof ', ' str ', ' subclasshook ', ' weakref ', 'age', 'course', 'name']
# The built in attributes of class is also returned along with the user defined attributes