相关疑难解决方法(0)

Python函数属性 - 使用和滥用

没有多少人知道这个功能,但Python的功能(和方法)可以有属性.看吧:

>>> def foo(x):
...     pass
...     
>>> foo.score = 10
>>> dir(foo)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name', 'score']
>>> foo.score
10
>>> foo.score += 1
>>> foo.score
11
Run Code Online (Sandbox Code Playgroud)

Python中此功能的可能用途和滥用情况是什么?我知道的一个好用途是PLY使用docstring将语法规则与方法相关联.但是自定义属性呢?有充分的理由使用它们吗?

python attributes function

181
推荐指数
7
解决办法
10万
查看次数

函数如何访问自己的属性?

是否可以从函数范围内访问python函数对象属性?

比如我们有

def f():
    return SOMETHING

f._x = "foo"
f()           # -> "foo"
Run Code Online (Sandbox Code Playgroud)

现在,如果我们想让_x属性内容"foo"返回,那么SOMETHING必须是什么?如果它甚至可能(简单)

谢谢

更新:

我也想做以下工作:

g = f
del f
g()          # -> "foo"
Run Code Online (Sandbox Code Playgroud)

更新2:

声明不可能(如果是这种情况),以及为什么,比提供如何伪造它的方式更令人满意,例如使用与函数不同的对象

python attributes closures scope function

39
推荐指数
4
解决办法
2万
查看次数

标签 统计

attributes ×2

function ×2

python ×2

closures ×1

scope ×1