Python 函数属性 - 使用和滥用 [英] Python function attributes - uses and abuses
问题描述
没有多少人知道这个特性,但是 Python 的函数(和方法)可以有 属性.瞧:
<预><代码>>>>定义 foo(x):... 经过...>>>foo.score = 10>>>目录(富)['__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'、'sss]>>>foo.score10>>>foo.score += 1>>>foo.score11这个特性在 Python 中有哪些可能的用途和滥用?我知道的一个很好的用途是 PLY 使用文档字符串将语法规则与一个方法.但是自定义属性呢?是否有充分的理由使用它们?
我通常使用函数属性作为注释的存储.假设我想用C#的风格来写(表示某个方法应该是Web服务接口的一部分)
class Foo(WebService):@webmethod定义栏(自我,arg1,arg2):...
然后我可以定义
def webmethod(func):func.is_webmethod = 真返回函数
然后,当webservice调用到来时,我查找方法,检查底层函数是否有is_webmethod属性(实际值无关),如果方法不存在或不打算调用则拒绝服务网络.
Not many are aware of this feature, but Python's functions (and methods) can have attributes. 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 ? One good use I'm aware of is PLY's usage of the docstring to associate a syntax rule with a method. But what about custom attributes ? Are there good reasons to use them ?
I typically use function attributes as storage for annotations. Suppose I want to write, in the style of C# (indicating that a certain method should be part of the web service interface)
class Foo(WebService):
@webmethod
def bar(self, arg1, arg2):
...
then I can define
def webmethod(func):
func.is_webmethod = True
return func
Then, when a webservice call arrives, I look up the method, check whether the underlying function has the is_webmethod attribute (the actual value is irrelevant), and refuse the service if the method is absent or not meant to be called over the web.
这篇关于Python 函数属性 - 使用和滥用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!