Python object properties with docstrings from a dict
在对象的init中,我想从iterable创建对象属性。例如:
1 2 3 4 5 6 7 8 9 10 11 12 | 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) |
这可以让我得到我想要的属性。然而,与定义相比,我失去了什么
1 2 3 4 | @property def name(self): """str: This class' name""" return self._name |
就是我现在不获取属性的docstrings。
我希望每个属性都有docstring(对于我的自动生成的文档),但是我也希望使用iterable而不是单独定义每个属性。例如,我可以将
我可以吃蛋糕吗?
只能在类上设置
只需生成
1 2 3 4 5 6 7 8 9 10 | 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) |