在调用函数对象之前,函数对象中的Python3.7函数属性不可用


def f():
f.created_by = "User1"
pass

f.created_by trows AttributeError:"function"对象没有属性"created_by"。即:

>>> f.created_by
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute 'created_by

但如果我在外部设置一个属性,它就可以正常工作。即:

>>> f.code = "function code"
>>> f.code
'function code'
>>> 

我只是想知道为什么我可以在不调用集合函数属性的情况下访问它,但不能从中检索另一个属性。

函数内部的代码只有在实际调用该函数时才会运行。所以你可以这样做:

f()
f.created_by

它将按照您希望的方式工作:(

最新更新