Python 函数属性 - 使用和滥用 [关闭] - Python function attributes - uses and abuses [closed]

10/14 10:05
阅读数 0

问题:

Closed . 关闭 This question needs to be more focused . 这个问题需要更加集中 It is not currently accepting answers. 它目前不接受答案。

Want to improve this question?想改善这个问题吗? Update the question so it focuses on one problem only by editing this post .更新问题,使其仅通过编辑这篇文章来关注一个问题。

Closed 6 years ago . 6年前关闭。

Not many are aware of this feature, but Python's functions (and methods) can have attributes .没有多少人知道这个特性,但是 Python 的函数(和方法)可以有属性 Behold:看:

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

What are the possible uses and abuses of this feature in Python ?这个特性在 Python 中有哪些可能的用途和滥用? One good use I'm aware of is PLY 's usage of the docstring to associate a syntax rule with a method.我知道的一个很好的用途是PLY使用 docstring 将语法规则与方法相关联。 But what about custom attributes ?但是自定义属性呢? Are there good reasons to use them ?有充分的理由使用它们吗?


解决方案:

参考一: https://en.stackoom.com/question/1PxF
参考二: https://stackoom.com/question/1PxF
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部