Python:具有DOT函数的变量之前是函数名称



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

def f(x):
    f.author = 'sunder'
    f.language = 'Python'
    print(x,f.author,f.language)
f(5)
`>>> 5 sunder Python`

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

来自官方文档:

程序员的注释:功能是一流的对象。在功能定义中执行的" DEF"语句定义了可以返回或传递的本地函数。嵌套函数中使用的自由变量可以访问包含def的函数的局部变量。

因此,函数是一个对象:

>>> f.__class__
<class 'function'>
>>> f.__class__.__mro__
(<class 'function'>, <class 'object'>)

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

>>> 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']

相关内容

最新更新