python - 关闭 : retrieve a variable given with the outer function

标签 python function variables scope closures

是否可以检索由外部函数给出的变量?

Python:

def html_tag(tag):
    print(" : <{t}>".format(t=tag))
    def wrap_text(msg):
        print("<{t}>{m}<{t}>".format(t=tag, m=msg))

    return wrap_text


print_h1 = html_tag("h1")
print_div = html_tag("div")
print_span = html_tag("span")
print_h1("h1 - test met h1")
print_div("div - mouse button")
print_span("span - tekst met tag")

就我而言,我想在不同的函数中查看/检索变量tag

link to the excuted python code

print ( "help(print_h1)   : ", help(print_h1), "")
print ( "dir(print_h1)    : ", dir(print_h1), "")
print ( "print_h1.__dir__ : ", (print_h1.__dir__), "")
#print (print_h1.tag, "")
print ( "print_h1         : ",print_h1.__closure__, "\n")
print ( "print_h1         : ",print_h1, "\n")

返回:

Help on function wrap_text in module __main__:

wrap_text(msg)

help(print_h1)   :  None 
dir(print_h1)    :  ['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__'] 
print_h1.__dir__ :  <built-in method __dir__ of function object at 0x7f2f42fbdb90> 
print_h1         :  (<cell at 0x7f2f42f73310: str object at 0x7f2f51f066b0>,) 

print_h1         :  <function html_tag.<locals>.wrap_text at 0x7f2f42fbdb90> 

所以当我这样尝试时 它不在 .__dir__ ... 的字典中

print (print_h1.tag)

错误

AttributeError                            Traceback (most recent call last)
<ipython-input-55-71ea208bcc8c> in <module>()
----> 1 print (print_h1.tag)

AttributeError: 'function' object has no attribute 'tag'

编辑 - 我想检索 tag 变量

print_h1.__closure__:  (<cell at 0x7f2f42f73310: str object at 0x7f2f51f066b0>,)

地址内存位置:x - 从上一个命令手动检索

import ctypes

x=0x7f2f51f066b0
# display memory address
print("Memory address - ", x)
  
# get the value through memory address
a = ctypes.cast(x, ctypes.py_object).value
  
# display
print("Value - ", a)

返回:

Memory address -  139841214899888
Value -  h1

最佳答案

__closure__ 是用户定义函数对象的(只读)属性: 它是包含函数自由变量绑定(bind)的cell的元组(或无)。

cell 对象具有(读和写)属性 cell_contents。这可用于获取/设置单元格的值。

注意cell类型可以通过types访问模块


code 对象是解释器使用的内部类型,可供用户访问。

co_freevars 是一个包含自由变量名称的元组


这里是一个关于如何获取函数参数值及其标识符的示例:

# html_tag: from the question

print_h1 = html_tag('h1')

# identifier of the parameter - with code obj
print(print_h1.__code__.co_freevars[0])
#tag

# value of the function's parameter - read
print(print_h1.__closure__[0].cell_contents)
#h1

# value of the function's parameter - write
print_h1.__closure__[0].cell_contents = 'h19'
print_h1('a')
#<h19>a<h19>

关于python - 关闭 : retrieve a variable given with the outer function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72547591/

相关文章:

Python - 遍历 dict。在字典中搜索元素

python - 使用默认配置的自定义 Django 日志配置

python - 如何在使用 tf.tile 时重现错误 'InvalidArgumentError : expected multiples argument to be a vector of length 2 but got length 3'

javascript - undefined variable 作为函数参数 javascript

javascript - 无法将 lodash 部分应用于使用 bluebird promisifyAll 创建的函数

Python 无法正确比较我分配的变量

python - 将 tensorflow 检查点保存到 .pb protobuf 文件

c++ - 有没有办法从 `std::function` 返回到指针?

javascript - 如何在 ruby​​ 中使用 javascript 中的变量?

javascript - 如何使用变量访问对象属性