dir 内部函数

dir inside function

Python 有一个很好的特性,可以提供一个对象的内容,就像它的所有方法和现有变量一样,称为 dir()。但是,当在函数中调用 dir 时,它只会查看函数的范围。因此,在函数中调用 dir() 与在函数外调用它具有不同的值。例如:

dir()
> ['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
def d():
  return dir()
d()
> []

有没有办法改变 d 中目录的范围?

dir() 没有参数 默认为当前范围(locals() 的键,但已排序)。如果你想要一个不同的范围,你必须传入一个对象。来自 documentation:

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.

对于全局范围,使用sorted(globals());这与在模块级别调用 dir() 的结果完全相同。