gpt4 book ai didi

python - 尝试在 python 中获取对象类型时出错

转载 作者:太空宇宙 更新时间:2023-11-03 15:01:27 25 4
gpt4 key购买 nike

我有一个主脚本,它导入了我一直在编写的另一个 python 库。该库包含以下命令:

print getattr(__builtins__, "list")

当我从库中调用它时,会产生以下错误:

'dict' object has no attribute 'list'

但是,如果我将相同的命令复制并粘贴到主脚本中,它就可以正常工作。有什么想法为什么这不起作用吗?

我的主文件的标题如下所示:

#/usr/bin/env python
from sys import argv
import re, sys, os, argparse
sys.path.extend(map(os.path.abspath, ['C:/Users/xxxx/scripts/modules/']))
import general

我的“通用”库的标题是:

#!/usr/bin/env python
from sys import argv
import re, sys, os, argparse

def getBuiltin(name):
##Convert a string into an attribute
try:
return getattr(__builtins__, name)
except Exception as e:
print "Unhandled type in function \"get_builtin\""
print name
print e
exit()

我是这样调用图书馆的:

print general.getBuiltin("list")

其中,“getBuiltin”是我的函数的名称

最佳答案

您还可以查看这个问题:Python: What's the difference between __builtin__ and __builtins__?

正如您在 akent 答案中看到的,内置在主模块和另一个模块中是不同的:

Straight from the python documentation: http://docs.python.org/reference/executionmodel.html

By default, when in the main module, builtins is the built-in module builtin (note: no 's'); when in any other module, builtins is an alias for the dictionary of the builtin module itself.

builtins can be set to a user-created dictionary to create a weak form of restricted execution.

CPython implementation detail: Users should not touch builtins; it is strictly an implementation detail. Users wanting to override values in the builtins namespace should import the builtin (no 's') module and modify its attributes appropriately. The namespace for a module is automatically created the first time a module is imported. Note that in Python3, the module builtin has been renamed to builtins to avoid some of this confusion.

关于python - 尝试在 python 中获取对象类型时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45060742/

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