问题描述
我有一个装饰器,它向 pack()
类添加 unpack()
和 NamedTuple
方法,以帮助我使用 python 的 struct
模块进行序列化(参见下面的代码)。
装饰器所做的一件事是添加一个 pack_format
属性,该属性包含 struct
函数使用的格式字符串。我想知道如何记录这个。
我曾尝试在作业中使用 #:
样式的注释,但没有奏效。
我尝试的另一件事是添加 pack_format
属性而不是属性。这种工作方式,因为 sphinx 现在包含文档字符串,但我无法以与 Sphinx 正常记录属性值相同的方式查看 pack_format 属性的值(记录下来非常有用)。
def fixed_format(pack_format: str):
def decorator(cls):
cls.pack_format = pack_format #: The serialization format.
# look for a pack_values() method,or default to __iter__
get_values = getattr(cls,'pack_values',cls.__iter__)
def pack(self) -> bytes:
"""Serialize the package payload.
This method was created by the :func:`fixed_format` decorator.
"""
return struct.pack(self.pack_format,*get_values(self))
ctor = getattr(cls,'unpack_values',cls)
def unpack(cls,buf: bytes):
"""Deserialize the package payload and return a new instance.
This class method was created by the :func:`fixed_format` decorator.
"""
# look for an unpack_values() class method,or default to the class constructor
values = struct.unpack(cls.pack_format,buf)
return ctor(*values)
cls.pack = pack
cls.unpack = classmethod(unpack)
return cls
return decorator
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)