[英]Python object properties with docstrings from a dict
在对象的初始化中,我想从一个可迭代对象创建对象属性。 例如:
class MyClass(object):
def __init__(self, parameters):
attributes = ['name',
'memory',
'regressors',
'use_const']
for attr_name in attributes():
try:
attr_val = parameters[attr_name]
except KeyError:
raise Error("parameters must contain {}".format(attr_name))
setattr(self, attr_name, attr_val)
这使我可以获得所需的属性。 但是,与定义相比,我所失去的
@property
def name(self):
"""str: This class' name"""
return self._name
是我现在没有获得属性的文档字符串。
我想为每个属性(对于我的自动生成的文档)使用docstrings,但是我也想使用可迭代的方法,而不必分别定义每个属性。 例如,是否可以将attributes
转换为以文档字符串为值的字典,并动态设置属性的文档字符串?
我可以吃我的蛋糕吗?
您只能在类上设置property
对象。 您可以循环执行此操作,但这必须在构建类而不是实例时完成。
只需生成property
对象:
def set_property(cls, name, attr, docstring):
def getter(self):
return getattr(self, attr)
prop = property(getter, None, None, docstring)
setattr(cls, name, prop)
for name in attributes:
attr = '_' + name
docstring = "str: This class' {}".format(name)
set_property(SomeClass, name, attr, docstring)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.