假设原始版本是这样的:
class BitsInteger:
"""BitsInteger docstring"""
def __init__(self, num):
pass
def singleton(cls):
return cls()
def singletonfunction(func):
return func()
@singletonfunction
def Bit():
"""A 1-bit BitField; must be enclosed in a BitStruct"""
return BitsInteger(1)
b = Bit
print("b.__doc__ :", b.__doc__)
用 Python3.5 运行它会得到输出:
b.__doc_ : BitsInteger docstring
这可能不是您所期望的。当我们使用python -i original.py 运行时,我们可以看看这里到底发生了什么:
>>> vars()
{'__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, 'b': <__main__.BitsInteger object at 0x7ff05d2ae3c8>, '__spec__': None, 'singletonfunction': <function singletonfunction at 0x7ff05d2b40d0>, 'singleton': <function singleton at 0x7ff05d30cd08>, '__cached__': None, 'BitsInteger': <class '__main__.BitsInteger'>, '__loader__': <_frozen_importlib.SourceFileLoader object at 0x7ff05d2eb4a8>, '__package__': None, 'Bit': <__main__.BitsInteger object at 0x7ff05d2ae3c8>, '__doc__': None}
>>>
如您所见,b 实际上是 BitsInteger 类型
原因是因为真正发生的事情是当你写的时候:
@singleton_function
def Bit():
"""Bit docstring"""
...
return BitsInteger(1)
你真的只是得到了语法糖:
def Bit():
"""Bit docstring"""
...
return BitsInteger(1)
Bit = singleton_function(Bit)
在这种情况下Bit 是singleton_function 的返回值,它实际上是BitsInteger。我发现当你去掉语法糖时,这里发生了什么会更清楚。
如果您想使用不会更改文档字符串的装饰器,我建议您使用 wrapt
import wrapt
class BitsInteger:
"""BitsInteger docstring"""
def __init__(self, num):
pass
def singleton(cls):
return cls()
@wrapt.decorator
def singletonfunction(func):
return func()
@singletonfunction
def Bit():
"""A 1-bit BitField; must be enclosed in a BitStruct"""
return BitsInteger(1)
b = Bit
print("b.__doc_ :", b.__doc__)
这个输出:
b.__doc_ : A 1-bit BitField; must be enclosed in a BitStruct
现在,当您查看 Vars() 时,您会看到 'b': <FunctionWrapper at 0x7f9a9ac42ba8 for function at 0x7f9a9a9e8c80> 不再是 BitInteger 类型。就我个人而言,我喜欢使用 wrapt,因为我可以立即得到我想要的东西。实现该功能并涵盖所有边缘情况需要付出努力,我知道 wrapt 已经过良好测试并且可以按预期工作。