我不确定这到底意味着什么或如何使用它,但是当涉及到函数时我遇到了这个功能。我能够动态地向函数添加属性。
这个有什么用以及它是如何发生的?我的意思是它毕竟是一个函数名,我们如何动态地向它添加属性?
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/