Reputation: 894
I'm working with the docx
library in Python, and I was hoping to create a subclass NewStyleDoc
of the Document
class from docx
. I attempted to do this as follows:
from docx import Document
class NewStyleDocument(Document):
# stuff
And I received the error:
TypeError: function() argument 1 must be code, not str
Which means Document
is actually a function. (I verified this with type(Document)
) My question is: can I define a class that inherits all of the properties of Document
? My ultimate goals is simple: I just want to do:
doc = NewStyleDocument()
and have some custom fonts. (Usually you have to modify styles each time you create a new document.) Maybe there is an easier way?
Upvotes: 2
Views: 6133
Reputation: 142136
The simplest method (as docx.Document
appears to be a factory function) is probably to just let it do what it needs to so you don't repeat, and wrap around it:
from docx import Document
def NewStyleDocument(docx=None):
document = Document(docx)
document.add_heading('Document Title', 0)
return document
mydoc = NewStyleDocument()
Upvotes: 4
Reputation: 1371
This is from the documentation. Your issue seems to be you are using a constructor built into the module, not into the object.
Document objects¶
class docx.document.Document[source]
WordprocessingML (WML) document. Not intended to be constructed directly. Use docx.Document() to open or create a document.
So you need to add another layer in there (Docx.document.Document)
Upvotes: 0