我正在构建一个 HTTP API,并将大量代码分解到一个超类中,该超类处理对对象集合的请求。在我的子类中,我指定操作应该在哪些数据库模型上进行,而超类负责其余的工作。
这意味着我不需要重新实现超类中的 get、post 等方法,但是,我想更改子类中的文档字符串,以便我可以拥有一些更具体于实际模型的文档端点正在运行。
继承父类功能但更改文档字符串的最简洁方法是什么?
示例:
class CollectionApi(Resource):
"""Operate on a collection of something.
"""
class Meta(object):
model = None
schema = None
def get(self):
"""Return a list of collections.
"""
# snip
def post(self):
"""Create a new item in this collection.
"""
# snip
class ActivityListApi(CollectionApi):
"""Operations on the collection of Activities.
"""
class Meta(object):
model = models.Activity
schema = schemas.ActivitySchema
具体来说,我需要
ActivityListApi
让 get
和 post
像 CollectionApi
一样运行,但我想要不同的文档字符串(为了自动文档化)。
我可以做到这一点:
def get(self):
"""More detailed docs
"""
return super(ActivityListApi, self).get()
但这看起来很混乱。
class CollectionApi(Resource):
"""Operate on a collection of something.
"""
def _get(self):
"""actual work... lotsa techy doc here!
the get methods only serve to have something to hang
their user docstrings onto
"""
pass
def get(self):
"""user-intended doc for CollectionApi"""
return self._get()
class ActivityListApi(CollectionApi):
def get(self):
"""user-intended doc for ActivityListApi"""
return self._get()
迟到总比不到好。实际上可以在声明类后直接修改
__doc__
方法属性来更改文档,同时保持原始方法不变。
以下是您的申请需要做的事情:
class CollectionApi(Resource):
"""Operate on a collection of something.
"""
class Meta(object):
model = None
schema = None
def get(self):
"""Return a list of collections.
"""
# snip
def post(self):
"""Create a new item in this collection.
"""
# snip
class ActivityListApi(CollectionApi):
"""Operations on the collection of Activities.
"""
class Meta(object):
model = models.Activity
schema = schemas.ActivitySchema
ActivityListApi.get.__doc__ = \
"""user-intended doc for `get`.
"""
ActivityListApi.post.__doc__ = \
"""user-intended doc for `post`.
"""