gpt4 book ai didi

python - 函数内部目录

转载 作者:行者123 更新时间:2023-12-02 02:22:33 25 4
gpt4 key购买 nike

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() 的结果完全相同。

关于python - 函数内部目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27931539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com