想要改进这个问题吗? 更新问题,使其只关注一个问题 editing this post .
关闭 7 年前。
没有多少人知道这个特性,但是 Python 的函数(和方法)可以有 attributes .看:
>>> 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
这个特性在 Python 中有哪些可能的用途和滥用?我知道的一个很好的用途是PLY使用文档字符串将语法规则与方法相关联。但是自定义属性呢?有充分的理由使用它们吗?
最佳答案
我通常使用函数属性作为注释的存储。假设我想写,C#的风格(表示某个方法应该是Web服务接口(interface)的一部分)
class Foo(WebService):
@webmethod
def bar(self, arg1, arg2):
...
那我可以定义
def webmethod(func):
func.is_webmethod = True
return func
然后,当webservice调用到来时,我查找方法,检查底层函数是否有is_webmethod属性(实际值无关),如果方法不存在或不打算调用,则拒绝服务网络。
https://stackoverflow.com/questions/338101/