python:函数中的变量,带有以函数名称开头的点

python: variables in a function with dot preceded by the function name

我需要理解这个概念,其中我们可以在函数定义中的变量名中使用点(.)。这里既没有类定义,也没有模块,Python不应该接受包含点的变量名。

1
2
3
4
5
6
7
def f(x):
    f.author = 'sunder'
    f.language = 'Python'
    print(x,f.author,f.language)

f(5)
`>>> 5 sunder Python`

请解释这是如何可能的,并为进一步的探索建议相关的文件。


官方文件:

Programmer’s note: Functions are first-class objects. A"def" statement executed inside a function definition defines a local function that can be returned or passed around. Free variables used in the nested function can access the local variables of the function containing the def.

所以,函数是对象:

1
2
3
4
>>> f.__class__
<class 'function'>
>>> f.__class__.__mro__
(<class 'function'>, <class 'object'>)

…这意味着它可以存储属性:

1
2
3
4
>>> f.__dict__
{'language': 'Python', 'author': 'sunder'}
 >>> dir(f)
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'author', 'language']