Python:是否可以修改内置函数属性的可写性?

时间:2021-05-07 15:12:23

标签: python attributes namespaces introspection

假设我想更改 print 的名称,以便我通过 pr('string') 调用它(并释放 print)。

print.__setattr__('__name__', 'pr')

给予

AttributeError: attribute '__name__' of 'builtin_function_or_method' objects is not writable

是否可以修改这种可写性?

编辑:

我知道函数指针可以随意改变,比如

pr = print

但是,我对修改属性的可能性很感兴趣。

这里没有真正的上下文,我想更多地了解基本属性。不过,在我的脑海里,人们可能会想象将命名空间翻译为 i18n 的工作:

builtin_functions = [name for name, obj in vars(builtins).items() 
                      if isinstance(obj, types.BuiltinFunctionType)]
for f in builtin_functions: 
    f.__setattr__('__name__', i18n_function(__getattribute__('__name__')))

2 个答案:

答案 0 :(得分:2)

您可以将 print 分配给不同的变量:

def whatever(text: str):
    pass

pr = print
print = whatever

pr("printing")
print("won't be printed")

只输出printing

答案 1 :(得分:2)

这里有两个相互竞争的“名称”概念。重要的是 Python 对名称的定义,它是在特定范围内引用值的标识符。此处,print 是内置作用域中的名称,它引用类型为 builtin_function_or_method 的值。

另一个是 __name__builtin_function_or_method 属性。它在名称查找中没有作用;更改 __name__ 属性不会影响您如何引用某物。下面是一个使用用户定义方法的示例,您可以更改其 __name__ 属性:

>>> def foo(): pass
...
>>> foo.__name__ = 'bar'
>>> bar
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'bar' is not defined
相关问题