python - 将属性附加到 Python 中的函数

标签 python python-3.x function

我不确定这到底意味着什么或如何使用它,但是当涉及到函数时我遇到了这个功能。我能够动态地向函数添加属性。

这个有什么用以及它是如何发生的?我的意思是它毕竟是一个函数名,我们如何动态地向它添加属性?

def impossible():
    print "Adding a bool"

impossible.enabled = True 
# I was able to just do this. And this is a function, how does this add up?

print(impossible.enabled) # No attribute error. Output: True

最佳答案

在Python中函数是对象,它们具有各种内部属性,并且还可以具有__dict__属性,并且与任何其他对象一样,__dict__中的任何内容都是变量该对象的。如果您在 impossible.enabled

之前和之后打印它,您就可以看到它
def impossible():
    print "Adding a bool"

print(impossible.__dict__) #  {}
impossible.enabled = True 
print(impossible.__dict__) #  {'enabled': True}

这不会以任何方式改变函数,因为大多数时候 __dict__ 是空的并且在函数中没有特殊值。 事实上它有点用,因为你可以在函数中使用它来存储静态变量,而不会弄乱你的全局名称

关于python - 将属性附加到 Python 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49839332/

相关文章:

c - C 中堆栈上的变量创建

python - 在grinder中跨代理、跨进程共享资源

python - 在 csv 文件中查找字符串时提取行

python - 有更好的方法来清理字典吗?

python - Pandas 面板 : How To Iterate Over the Minor Axis?

python-3.x - 使用win32模块有一个透明的Python窗口

c++ - 调用同名函数

python - 获取函数的关键字参数,Python

python - 从 Excel 中读取和比较坐标

python - 将字典与行值映射