gpt4 book ai didi

python-3.x - python : variables in a function with dot preceded by the function name

转载 作者:行者123 更新时间:2023-12-04 14:24:03 25 4
gpt4 key购买 nike

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

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

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

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

最佳答案

来自官方 documentation :

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.



所以,函数是一个对象:
>>> 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']

关于python-3.x - python : variables in a function with dot preceded by the function name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49649588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com