相关疑难解决方法(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中更改函数的repr吗?

我只看过__repr__在类定义中设置方法的示例.是否__repr__可以在定义中或定义后更改for函数?

我试图没有成功......

>>> def f():
    pass
>>> f
<function f at 0x1026730c8>
>>> f.__repr__ = lambda: '<New repr>'
>>> f
<function __main__.f>
Run Code Online (Sandbox Code Playgroud)

python function repr

14
推荐指数
3
解决办法
4119
查看次数

标签 统计

function ×2

python ×2

attributes ×1

repr ×1