我正在编写一个轻量级类,其属性旨在可公开访问,并且有时仅在特定实例中被覆盖.在Python语言中没有为类属性或任何类型的属性创建文档字符串的规定.记录这些属性的可接受方式是什么?目前我正在做这样的事情:
class Albatross(object):
"""A bird with a flight speed exceeding that of an unladen swallow.
Attributes:
"""
flight_speed = 691
__doc__ += """
flight_speed (691)
The maximum speed that such a bird can attain.
"""
nesting_grounds = "Raymond Luxury-Yacht"
__doc__ += """
nesting_grounds ("Raymond Luxury-Yacht")
The locale where these birds congregate to reproduce.
"""
def __init__(self, **keyargs):
"""Initialize the Albatross from the keyword arguments."""
self.__dict__.update(keyargs)
Run Code Online (Sandbox Code Playgroud)
这将导致类的docstring包含初始标准docstring部分,以及通过扩充赋值为每个属性添加的行__doc__.
虽然在文档字符串样式指南中似乎没有明确禁止这种样式,但它也没有作为选项提及.这里的优点是它提供了一种方法来记录属性及其定义,同时仍然创建一个可呈现的类docstring,并避免编写重复来自docstring的信息的注释.我仍然有点生气,我必须实际写两次属性; 我正在考虑使用docstring中值的字符串表示来至少避免重复默认值.
这是否是对特设社区公约的毁灭性违反?好吗?有没有更好的办法?例如,可以创建包含属性值和文档字符串的字典,然后__dict__在类声明的末尾将内容添加到类和docstring中; 这样可以减少两次输入属性名称和值的需要. 编辑:我认为,这最后一个想法实际上是不可能的,至少不是没有从数据动态构建整个类,这似乎是一个非常糟糕的想法,除非有其他理由这样做. …
是否可以将docstring用于普通变量?例如,我有一个名为的模块t
def f():
"""f"""
l = lambda x: x
"""l"""
Run Code Online (Sandbox Code Playgroud)
而我呢
>>> import t
>>> t.f.__doc__
'f'
Run Code Online (Sandbox Code Playgroud)
但
>>> t.l.__doc__
>>>
Run Code Online (Sandbox Code Playgroud)
示例类似于PEP 258(搜索"this is g").
我应该制作几个文档字符串,还是仅存一个(我应该把它放在哪里)?
@property
def x(self):
return 0
@x.setter
def x(self, values):
pass
Run Code Online (Sandbox Code Playgroud)
我看到property()接受doc参数.
有没有一种方法可以以与方法和函数文档字符串相同的方式自动生成数据类的文档字符串?我通过帮助/搜索没有找到任何有用的东西
from dataclasses import dataclass
@dataclass
class ExtractionConfig:
"""
"""
gcp_bucket: str = None
gcp_key: str = None
log_file: str = None
log_backup_count: int = 3
delete_remotely: bool = True
Run Code Online (Sandbox Code Playgroud)
当我尝试手动添加它们时,我得到未解析的引用: