【发布时间】:2020-08-06 09:21:33
【问题描述】:
在python-docx库中,Document对象是使用docx.api文件中的构造函数func:docx.Document创建的
def Document(docx=None):
"""
Return a |Document| object loaded from *docx*, where *docx* can be
either a path to a ``.docx`` file (a string) or a file-like object. If
*docx* is missing or ``None``, the built-in default document "template"
is loaded.
"""
docx = _default_docx_path() if docx is None else docx
document_part = Package.open(docx).main_document_part
if document_part.content_type != CT.WML_DOCUMENT_MAIN:
tmpl = "file '%s' is not a Word file, content type is '%s'"
raise ValueError(tmpl % (docx, document_part.content_type))
return document_part.document
但是可以应用于对象的方法位于文件 docx.document.Document 中。下面是截图
类文档(ElementProxy): """WordprocessingML (WML) 文档。
Not intended to be constructed directly. Use :func:`docx.Document` to open or create
a document.
"""
__slots__ = ('_part', '__body')
def __init__(self, element, part):
super(Document, self).__init__(element)
self._part = part
self.__body = None
def add_heading(self, text="", level=1):
"""Return a heading paragraph newly added to the end of the document.
The heading paragraph will contain *text* and have its paragraph style
determined by *level*. If *level* is 0, the style is set to `Title`. If *level*
is 1 (or omitted), `Heading 1` is used. Otherwise the style is set to `Heading
{level}`. Raises |ValueError| if *level* is outside the range 0-9.
"""
if not 0 <= level <= 9:
raise ValueError("level must be in range 0-9, got %d" % level)
style = "Title" if level == 0 else "Heading %d" % level
return self.add_paragraph(text, style)
def add_page_break(self):
"""Return newly |Paragraph| object containing only a page break."""
paragraph = self.add_paragraph()
paragraph.add_run().add_break(WD_BREAK.PAGE)
return paragraph
def add_paragraph(self, text='', style=None):
"""
Return a paragraph newly added to the end of the document, populated
with *text* and having paragraph style *style*. *text* can contain
tab (``\\t``) characters, which are converted to the appropriate XML
form for a tab. *text* can also include newline (``\\n``) or carriage
return (``\\r``) characters, each of which is converted to a line
break.
"""
return self._body.add_paragraph(text, style)
我想了解 - 如何在函数创建的对象上使用类 Document 的方法 - docx.Document 。两者之间的联系是什么?
另外,如何使用新方法扩展类 Document 并将其应用于由函数创建的对象。例如 - 下面不起作用
from docx.document import Document as doc1
class doc_new(doc1):
def new_prop(self, q):
self.name = q
return self.name
document = Document()
x = document.new_prop("John")
print(x)
【问题讨论】:
标签: python python-docx