python - 为什么这个未绑定(bind)的变量可以在 Python (pyquery) 中工作?

标签 python variables pyquery

代码来自pyquery的指南

from pyquery import PyQuery
d = PyQuery('<p class="hello">Hi</p><p>Bye</p>')
d('p').filter(lambda i: PyQuery(this).text() == 'Hi')

我的问题是第 3 行的 this 是一个未绑定(bind)的变量,在当前环境中从未定义过,但上面的代码仍然有效。

它是如何工作的?为什么它不提示 NameError: name 'this' is not defined

似乎在https://bitbucket.org/olauzanne/pyquery/src/c148e4445f49/pyquery/pyquery.py#cl-478发生了什么事, 谁能解释一下?

最佳答案

这是通过 Python 的 func_globals 魔法完成的,也就是

A reference to the dictionary that holds the function’s global variables — the global namespace of the module in which the function was defined.

如果您深入研究 PyQuery 代码:

def func_globals(f):
    return f.__globals__ if PY3k else f.func_globals

def filter(self, selector):
    if not hasattr(selector, '__call__'):
        return self._filter_only(selector, self)
    else:
        elements = []
        try:
            for i, this in enumerate(self):

                # The magic happens here
                func_globals(selector)['this'] = this

                if callback(selector, i):
                    elements.append(this)

        finally:
            f_globals = func_globals(selector)
            if 'this' in f_globals:
                del f_globals['this']
        return self.__class__(elements, **dict(parent=self))

关于python - 为什么这个未绑定(bind)的变量可以在 Python (pyquery) 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11814813/

相关文章:

python - 有没有一种简单的方法可以计算 Pandas value_counts 系列的均值和标准差?

python - 停止 pyquery 在源 HTML 中没有空格的地方插入空格?

python - numba 不接受 dtype=object 的 numpy 数组

python - 在 RaspberryPi 中安装 OpenCV 以与 Python 一起使用的正确方法

php - 使用 Sql 查询显示变量的错误值

php - 取名为数组键名的变量

c++ - 如何在具有常量类变量的类中声明常量数组?

python - 如何使这个 Python 类定义代码不那么难看

python - 在Python中将字符串转换为十进制