Python 函数属性 - 使用和滥用

没有多少人知道这个特性,但是 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/

相关文章:

linux - 在 linux 中显示磁盘事件的类似 htop 的工具

python - 如何为类对象创建自定义字符串表示?

linux - 在 Linux 上的 bash 中获取昨天的日期,DST 安全

python - 在 NumPy 中将索引数组转换为 one-hot 编码数组

linux - 什么是不间断进程?

linux - 如何强制 CIFS 连接卸载

linux - 在 SSH session 中查找客户端的 IP 地址

linux - 如何阅读 shell 命令的源代码?

python - 在 Python 中创建具有初始容量的列表

python - 遍历列表中的每两个元素