Home >Backend Development >Python Tutorial >Python内置函数dir详解
1.命令介绍
最近学习并使用了一个python的内置函数dir,首先help一下:
dir()
dir([object]) -> list of strings
Return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attributes reachable from it:
No argument: the names in the current scope.
Module object: the module attributes.
Type or class object: its attributes, and recursively the attributes of
its bases.
Otherwise: its attributes, its class's attributes, and recursively the
attributes of its class's base classes.
if __name__ == '__main__':
print("dir without arguments:", dir())
print("dir class A:", dir(A))
print("dir class A1:", dir(A1))
a = A1()
print("dir object a(A1):", dir(a))
print("dir function a.a:", dir(a.a))
if __name__ == '__main__':
print("dir module A:", dir(A))
4.如何找到当前模块下的类
这是一个烦恼较长时间的一个问题,也没有搜到详细的解决方法,下面是我的集中实现方法。
4.1.方法一:在module下面直接调用
比如在上面的A.py最下面添加一行,即可在后续的代码中可以使用selfDir来查找当前的module下的类,修改后的代码如下:
if __name__ == '__main__':
print("dir without arguments:", dir())
print("dir class A:", dir(A))
print("dir class A1:", dir(A1))
a = A1()
print("dir object a(A1):", dir(a))
print("dir function a.a:", dir(a.a))
print("dir current file:", curModuleDir)
4.2.方法二:import当前module
把当前module和别的import一样引用,代码如下:
if __name__ == '__main__':
print("dir without arguments:", dir())
print("dir class A:", dir(A))
print("dir class A1:", dir(A1))
a = A1()
print("dir object a(A1):", dir(a))
print("dir function a.a:", dir(a.a))
print("dir current file:", dir(this))
class A:
def a(self):
pass
class A1(A):
def a1(self):
pass
if __name__ == '__main__':
print("dir without arguments:", dir())
print("dir class A:", dir(A))
print("dir class A1:", dir(A1))
a = A1()
print("dir object a(A1):", dir(a))
print("dir function a.a:", dir(a.a))
print("dir current file:", dir(sys.modules[__name__])) # 使用__name__获取当前module对象,然后使用对象获得dir