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

查看:116
本文介绍了Python函数属性 - 使用和滥用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不是很多都知道这个功能,但是Python的功能(和方法)可以有属性 。看哪:

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

什么是在Python此功能的可能用途和滥用?一个很好的利用我所知道的是 PLY 的文档字符串到语法规则与方法关联的使用。但对于自定义属性?是否有使用它们很好的理由?

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 ?

推荐答案

我通常使用的功能属性作为存储注解。假设我想写点什么,在C#的风格(表示一定的方法应该是Web服务接口的一部分)

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):
         ...

然后我可以定义

def webmethod(func):
    func.is_webmethod = True
    return func

然后,当Web服务调用到达时,我抬头看的方法,检查底层函数是否具有is_webmethod属性(实际值无关),以及拒绝服务,如果方法不存在或不是意味着要叫了过来网页。

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆