파이썬 클래스 상속에서 독 스트링 상속
파이썬에서 클래스 상속을 시도하고 있습니다. 각 클래스와 상속 된 클래스가 좋은 독 스트링을 갖기를 바랍니다. 따라서 상속 된 클래스에 대해 다음과 같이하고 싶습니다.
- 기본 클래스 독 스트링 상속
- docstring에 관련 추가 문서를 추가 할 수 있습니다.
클래스 상속 상황에서 이런 종류의 독 스트링 조작을 수행하는 (아마도 우아하거나 비단뱀 같은) 방법이 있습니까? 다중 상속은 어떻습니까?
당신은 유일한 사람이 아닙니다! comp.lang.python
얼마 전에 이에 대한 논의가 있었고 레시피가 만들어졌습니다. 여기에서 확인 하십시오 .
"""
doc_inherit decorator
Usage:
class Foo(object):
def foo(self):
"Frobber"
pass
class Bar(Foo):
@doc_inherit
def foo(self):
pass
Now, Bar.foo.__doc__ == Bar().foo.__doc__ == Foo.foo.__doc__ == "Frobber"
"""
from functools import wraps
class DocInherit(object):
"""
Docstring inheriting method descriptor
The class itself is also used as a decorator
"""
def __init__(self, mthd):
self.mthd = mthd
self.name = mthd.__name__
def __get__(self, obj, cls):
if obj:
return self.get_with_inst(obj, cls)
else:
return self.get_no_inst(cls)
def get_with_inst(self, obj, cls):
overridden = getattr(super(cls, obj), self.name, None)
@wraps(self.mthd, assigned=('__name__','__module__'))
def f(*args, **kwargs):
return self.mthd(obj, *args, **kwargs)
return self.use_parent_doc(f, overridden)
def get_no_inst(self, cls):
for parent in cls.__mro__[1:]:
overridden = getattr(parent, self.name, None)
if overridden: break
@wraps(self.mthd, assigned=('__name__','__module__'))
def f(*args, **kwargs):
return self.mthd(*args, **kwargs)
return self.use_parent_doc(f, overridden)
def use_parent_doc(self, func, source):
if source is None:
raise NameError, ("Can't find '%s' in parents"%self.name)
func.__doc__ = source.__doc__
return func
doc_inherit = DocInherit
독 스트링을 쉽게 연결할 수 있습니다.
class Foo(object):
"""
Foo Class.
This class foos around.
"""
pass
class Bar(Foo):
"""
Bar class, children of Foo
Use this when you want to Bar around.
parent:
"""
__doc__ += Foo.__doc__
pass
However, that is useless. Most documentation generation tool (Sphinx and Epydoc included) will already pull parent docstring, including for methods. So you don't have to do anything.
Not particularly elegant, but simple and direct:
class X(object):
"""This class has a method foo()."""
def foo(): pass
class Y(X):
__doc__ = X.__doc__ + ' Also bar().'
def bar(): pass
Now:
>>> print Y.__doc__
This class has a method foo(). Also bar().
A mixed stile that can preserve both the inherited docstring syntax and the preferred ordering can be:
class X(object):
"""This class has a method foo()."""
def foo(): pass
class Y(X):
""" Also bar()."""
__doc__ = X.__doc__ + __doc__
def bar(): pass
With the same output as Alex's one:
>>> print Y.__doc__
This class has a method foo(). Also bar().
Thin ice: playing with docstring can make your module unusable with python -OO
, expect some:
TypeError: cannot concatenate 'str' and 'NoneType' objects
I wrote custom_inherit to provide some simple, light weight tools for handling docstring inheritance.
It also comes with some nice default styles for merging different types of docstrings (e.g. Numpy, Google, and reST formatted docstrings). You can also provide your own style very easily.
Overlapping docstring sections will defer to the child's section, otherwise they are merged together with nice formatting.
참고URL : https://stackoverflow.com/questions/2025562/inherit-docstrings-in-python-class-inheritance
'Programing' 카테고리의 다른 글
Bubble EditText에 문의 (0) | 2020.09.12 |
---|---|
CI 서버 비교? (0) | 2020.09.12 |
IPv6 앱 스토어 거부 (0) | 2020.09.12 |
DownloadManager를 사용하여 활동 내에서 다운로드 진행률 표시 (0) | 2020.09.12 |
RSpec : let과 before 블록의 차이점은 무엇입니까? (0) | 2020.09.11 |