使用 getattr() 访问内置函数

Using getattr() to access built-in functions

我想使用 getattr() 访问 Python 的内置函数。这可能吗?

例如:

getattr(???, 'abs')

我知道我可以简单地做到:

>>> abs
<built-in function abs>

但是我想用getattr,因为关键字名称是字符串。

builtins 模块:

您可以尝试导入 builtins 模块:

>>> import builtins
>>> getattr(builtins, 'abs')
<built-in function abs>
>>> 

documentation所述:

This module provides direct access to all ‘built-in’ identifiers of Python; for example, builtins.open is the full name for the built-in function open(). See Built-in Functions and Built-in Constants for documentation.

所以上面说的builtins.open就是open函数。所以 abs 是一样的 builtins.absabs 是一样的。但对于 gettatrgetattr(builtins, 'abs') 也与 builtins.abs 相同。

原文__bultins__(不推荐):

您可以尝试从 __builtins__:

>>> getattr(__builtins__, 'abs')
<built-in function abs>
>>> 

documentation所述:

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 builtins module and modify its attributes appropriately.

The builtins namespace associated with the execution of a code block is actually found by looking up the name __builtins__ in its global namespace; this should be a dictionary or a module (in the latter case the module’s dictionary is used). By default, when in the main module, __builtins__ is the built-in module builtins; when in any other module, __builtins__ is an alias for the dictionary of the builtins module itself.

如您所见,不推荐,通常 __builtins__ 是一个 dict,而不是一个模块。

如果您在模块中编写代码,__builtins__ 将 return 模块的 return 字典别名,这将给出如下内容:{..., 'abs': <built-in function abs>, ...}.

有关 getattr 的更多信息:

只是为了对 getattr 有更多的了解,如 documentation 中所述:

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

所以:

>>> import builtins
>>> getattr(builtins, 'abs')
<built-in function abs>
>>> 

等同于:

>>> import builtins
>>> builtins.abs
<built-in function abs>
>>> 

所以你可能想知道因为:

>>> abs
<built-in function abs>

给出同样的东西,为什么我们不能这样做:

getattr(abs)

我们不能这样做的原因是 getattr 应该调用 methods/functions/classes of a classes/modules.

使用getattr(builtins, 'abs')的原因是因为builtins是一个模块而abs是一个class/method,它存储了所有内置的Python关键字作为该模块中的方法。

所有关键字都显示在此 page 文档中。