Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python3-将函数替换为print()_Python_Python 3.x - Fatal编程技术网

Python3-将函数替换为print()

Python3-将函数替换为print(),python,python-3.x,Python,Python 3.x,我正试图为print()函数编写一个替换函数;我想了解Python 3在这里做什么 考虑以下两个Python 3源文件: file.py: def in_a_file(): print("this is in a file") minimal.py: import builtins from file import * def test(): print("this is a test") def printA(*args, **kw

我正试图为
print()
函数编写一个替换函数;我想了解Python 3在这里做什么

考虑以下两个Python 3源文件:

file.py:

def in_a_file():
    print("this is in a file")
minimal.py:

import builtins
from file import *

def test():
    print("this is a test")

def printA(*args, **kwargs):
    builtins.print("A: ", end="")
    builtins.print(*args, **kwargs)

print = printA

test()
in_a_file()
当我运行minimal.py时,我得到以下输出:

A: this is a test
this is in a file
因此,很明显,赋值
print=printA
改变了函数
test()
print()
的行为,而不是函数
file()
中的行为

为什么?


还有,是否有代码可以放入minimal.py中,类似地改变函数
file()
print()
的行为?

名称查找大致由所有模块共享
内置的
名称空间,每个模块都有自己的
全局的
名称空间,然后是嵌套的函数/类名称空间。
打印
功能存在于
内置
中,因此默认情况下在所有模块中都可见

minimal.py
中的赋值
print=printA
minimal
的全局命名空间添加了一个新名称
print
。这意味着
minimal.print
shadows
builtins.print
minimal
模块内。此更改在任何其他模块中都不可见,因为每个模块都有一个单独的模块全局命名空间

要在所有模块中更改
打印
,请重新分配
内置打印

导入内置项
_real\u print=内置打印
def printA(*args,**kwargs):
_真实打印(“A:,end=”“)
_真实打印(*args,**kwargs)
builtins.print=printA

模块有自己的名称空间,它不使用导入它的文件中定义的变量。@Barmar我想你是对的,但是你能详细说明一下吗?我不明白“它不使用导入它的文件中定义的变量”如何解释我所看到的。或者如何获得我想要的行为,即改变模块中print()的工作方式。这是否回答了您的问题?这回答了你的问题吗?每个模块都有自己的名称空间,在其中查找变量名。因此,文件中的变量
print
file.py
中的变量不同。这样做是为了使模块作者不必担心他们的变量可能与调用者中的变量冲突。